PDA

View Full Version : [HOW TO - vB4] Rendering templates and registering variables - a short guide


Pages : [1] 2

cellarius
16 Nov 2009, 08:41
Introduction

Starting with vB4, templates no longer get output using eval:
eval('$mytemplate = "' . fetch_template('mytemplate') . '";');is outdated.
What's more: Variables and arrays from plugins that are executed on a page no longer can automatically be accessed in the templates of that page. They need to be registered first.
.
Basic functionality to render templates and register all variables/arrays you want to use inside

/* Some Code, setting variables, (multidimensional) array */
$my_var = "abc";
$my_array = array(
'key1' => 'value1',
'key2' => array('
'key21' => 'value21',
'key22' => 'value22'
')
);

/* render template and register variables */
$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$templater->render();

The first line provides the template that is to be rendered, using the new vB_Template class (vB_Template::create). The method gets passed the name of the template as an argument.
The following two lines register a variable and an array that we want to use in our template. Arguments passed are 1. the name you want to use to access the variable, and 2. the variable from the code you want to register. You can register as many variables/arrays as you want. Just remember you have to register every variable and array that you want to use in your custom template in this way. If you don't register them, they will not be available.
The fourth line renders the template ($templater->render()). In the template you know will be able to use the registered variables/arrays in this way:
{vb:raw my_var}
{vb:raw my_array.key1}
{vb:raw my_array.key2.key21}Note the last one: multidimensional arrays are perfectly possible.
.
.
.
Now, with the result of the rendering we can do several things:
.
Output template directly - custom pages

$templater = vB_Template::create('mytemplate');
$templater->register_page_templates();
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
print_output($templater->render());This immediatly outputs the template. Use this if you have created your own page, for example.
Note the second line, which is special for this type of use:
$templater->register_page_templates();This auto-registers the page level templates header, footer and headinclude that you will use in the template of your custom page.
.
Use a template hook

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$template_hook[forumhome_wgo_pos2] .= $templater->render();The template will be shown using the choosen template hook (for example: $template_hook[forumhome_wgo_pos2]). See the dot before the = in the last line? The hook may be used by other modifications, too, so we don't want to overwrite it, but rather append our code to it, conserving everything that might already be there.
.
Save into a variable for later use in custom template

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$mytemplate_rendered = $templater->render();Now we have saved the rendered template into a variable. This variable in turn we can later on register in another template, if we want:
$templater = vB_Template::create('my_other_template');
$templater->register('my_template_rendered', $my_template_rendered);
print_output($templater->render());Again, inside my_other_template we now could call
{vb:raw my_template_rendered}If you're running the first template call inside a loop, you may want to use .= instead of = in the last line, so that the results of every loop get added instead of overwriting the existing. But that depends, of course.
.
Save into an array and preregister to use in an existing/stock template

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$templatevalues['my_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);

This is another, more flexible method to save the rendered template into a variable for future use in an already existing template. In this example, we want to show our own rendered template on forumhome.
Problem is: We have no direct way to register variables for already existing templates like FORUMHOME. It's created and rendered in the files, and we don't want to mess there.
To help with this, a new method was created for vB_Template class, called preRegister. Using this, we can pass our data to FORUMHOME before it is rendered. Note that the data needs to be saved into an array ($templatevalues['my_insertvar']), a simple variable will throw an error. In the last line the array is preregistered; you need to pass as arguments 1. the name of the existing template and 2. the array that contains the data. Again, this can be done for as many arrays as needed.
Of course, the preRegister functionality can be used for any kind of variables or arrays, no matter whether you have saved a rendered template (like in our example) into it or it contains just a simple boolean true/false statement. To access the data inside the template it was preregistered for use:
{vb:raw my_insertvar}Note: it is not {vb:raw templatevalues.my_insertvar}!

Essentially the same as what I put for preRegister would be the following two lines. They could replace the last two lines in the above php codebox:
$my_insertvar = $templater->render();
vB_Template::preRegister('FORUMHOME',array('my_insertvar ' => $my_insertvar));
Of course you could add further pairs to that array if you need to preregister more than one variable.
.
.
Bonus track: ...whatever you do, cache your templates!

Now you know how to get your templates on screen - once you succeeded in doing that, make sure to do it in a fast and ressource saving manner: make use of vB's template cache. To see whether your templates are cached or not, activate debug mode by adding $config['Misc']['debug'] = true;to your config.php (don't ever use that on your live site!). Among the debug info is a list of all templates called, and non-cached templates will show up in red.

To cache your templates, add a plugin at hook cache_templates with the following code:

// for a single template
$cache[] = 'mytemplate';

// for more than one templates in one step
$cache = array_merge((array)$cache,array(
'mytemplate',
'myothertemplate',
'mythirdtemplate'
));.
.
Hope this helps!
-cel

----
Addendum - There are now two blog posts on vb.com related to this topic:
http://www.vbulletin.com/forum/entry.php?2387-Pushing-your-variables-to-vBulletin-4-templates
http://www.vbulletin.com/forum/entry.php?2388-Using-custom-templates-within-your-own-vBulletin-4-based-files

Lynne
16 Nov 2009, 16:29
Great article, cellarius! Thanks for taking the time to write this out.

cellarius
16 Nov 2009, 16:35
I saw the same questoins over and over again, and you and others heroically answering the same time and again, so I thought this might come in handy. That's the system as I managed to grasp it up to now, and I myself learned while typing it down. However, I'd happily add any suggestions and improvements :)

Shadab
17 Nov 2009, 08:48
Thanks for the write up, Cellarius. :)

Btw, shouldn't {vb:raw my_array.value1} be {vb:raw my_array.key1} in the third codebox ?
(which would output "value1")

cellarius
17 Nov 2009, 09:03
Thanks for the write up, Cellarius. :)

Btw, shouldn't {vb:raw my_array.value1} be {vb:raw my_array.key1} in the third codebox ?
(which would output "value1")
Of course, thanks for pointing this out. Corrected.

--------------- Added 1258449197 at 1258449197 ---------------

There's two blog posts on this on vb.com:
http://www.vbulletin.com/forum/entry.php?2388-Using-custom-templates-within-your-own-vBulletin-4-based-files
http://www.vbulletin.com/forum/entry.php?2387-Pushing-your-variables-to-vBulletin-4-templates

Shadab
17 Nov 2009, 13:18
Of course, thanks for pointing this out. Corrected.
Not a problem!

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Another note; on multidimensional arrays...
Suppose you have a nested / multidimensional array set, like:

// Array declaration & assignment

$multiDim = array(
'level1' => array(
'foo' => 'one',
'bar' => 'two',
'baz' => 'three',
'qux' => 'four'
),
'test' => 'testval'
);

// Variable Registration

vB_Template::preRegister(
'header', array('multiDim' => $multiDim)
);


You can chain the array 'keys' like in the second example:

{vb:raw multiDim.test} <!-- Output: testval -->
{vb:raw multiDim.level1.baz} <!-- Output: three -->

Jeweetog
17 Nov 2009, 16:39
Hi,

How do i add a variable in form home template?

Im trying to do this:

Display stats on the forumhome yes/no

Display chatbox stats on the forumhome.
Don't forget to add the $mgc_cb_evo_stats variable in the FORUMHOME template where you want to display them otherwise they won't appear.
Warning : Add 4 sql queries on the forumhome.
For the users of a vBulletin version prior to 3.7.2, you will have to manually add the $mgc_cb_evo_stats var in the FORUMHOME template where you want the stats to appear.


How do i get this done guys?

Thanks in advance!

cellarius
17 Nov 2009, 17:32
You did not like my answer in the other thread?
You are posting this question in the vB4 subforum, so I gather you want to do this in vB4. If the mod's php code is not altered to adapt to vB4, there is no way of showing the variable in the template at this time. In vB4, variables need to be registered to be available in templates.
The mod clearly has not been updated for vB4. This very likely is not only a template rendering question, and this is not the place to discuss the porting of other peoples modifications. If you want to try anyway, the answer is in the article, look at the "Save into an array and preregister to use in an existing/stock template" part.

Jeweetog
17 Nov 2009, 18:35
You did not like my answer in the other thread?

The mod clearly has not been updated for vB4. This very likely is not only a template rendering question, and this is not the place to discuss the porting of other peoples modifications. If you want to try anyway, the answer is in the article, look at the "Save into an array and preregister to use in an existing/stock template" part.


I don't know about whether this is a rendering question or not. All i know is i have to alter something. Since you where kind enough to help me out by pointing me to this thread, i dropped the question here too, after reading what has been said up here.

Now i just read that part where you pointed me out, it doesn't say what file i have to open and at what line i have to insert some code.

Isn't that how it works?

cellarius
17 Nov 2009, 19:30
Sorry for being honest, but this is not how it works and it is quite obvious that you do not know what you are doing.

Of course "something" has to be done, but I do not know that mod, and therefore can not tell you what exactly will have to be done to make it vB4 compatible. It's not like there is a file in every mod that needs tampering that could be pointed out to you, where you do some mechanical search and replace and everything is fine. That's just not how it works, and this thread is not about updating the particular mod you are so interested in, but about helping coders to update their work. What has to be done is different for every single one of the hundreds of mods out there, and this article tries to provide just some of the many tools needed for that work.

The author of that mod will have to update his work, and you will have to be patient until he does - just like anyone else. If he decides not to do that you can pay someone to do it, or you can do it yourself if you have the skills. If that is not sufficient to you, you may ask in the thread for that modification, but be prepared that mod authors will be annoyed if dozens of users spam their threads with questions that go "are you not yet done", "when will you be updating this" and stuff.

Please read the announcement regarding this: http://www.vbulletin.org/forum/showthread.php?t=228073

bobster65
17 Nov 2009, 19:44
Just wanted to thank you for this article.. I had been messing around on my own for a few hours on two of my mods that involved FORUMHOME and after reading your article (specially the last part) both my mods are now up and running smoothly on vb4 !!

CHEERS to Cellarius!

Jeweetog
17 Nov 2009, 20:15
Sorry for being honest, but this is not how it works and it is quite obvious that you do not know what you are doing.

Of course "something" has to be done, but I do not know that mod, and therefore can not tell you what exactly will have to be done to make it vB4 compatible. It's not like there is a file in every mod that needs tampering that could be pointed out to you, where you do some mechanical search and replace and everything is fine. That's just not how it works, and this thread is not about updating the particular mod you are so interested in, but about helping coders to update their work. What has to be done is different for every single one of the hundreds of mods out there, and this article tries to provide just some of the many tools needed for that work.

The author of that mod will have to update his work, and you will have to be patient until he does - just like anyone else. If he decides not to do that you can pay someone to do it, or you can do it yourself if you have the skills. If that is not sufficient to you, you may ask in the thread for that modification, but be prepared that mod authors will be annoyed if dozens of users spam their threads with questions that go "are you not yet done", "when will you be updating this" and stuff.

Please read the announcement regarding this: http://www.vbulletin.org/forum/showthread.php?t=228073


I'm not trying to do an update. Nor am I trying to port or convert the mod to vb4. I, myself uses vb 3.8.4.

This mod has a few options. And one of the options out there tells you that if you activate 'this' option you have to add the $mgc_cb_evo_stats variable in the forumhome template.

Althought its about a particular mod, but I got the impression that this is something that is outside the scope of the mods explanation, looking at the explanation on how to do it, which is rather 'short'.

You misunderstood me, lets just leave it to that. Now if you don't mind, have a nice evening.

cellarius
17 Nov 2009, 20:32
I'm not trying to do an update. Nor am I trying to port or convert the mod to vb4. I, myself uses vb 3.8.4.
Then why in heaven do you post in an article that discusses vB4 programming techniques? If you need support for a mod the one and only place to go is the thread for this mod.

winstone
17 Nov 2009, 23:38
Just wanted to thank you guys both cellarius and Shadab, I've made a lot of progress on porting some major mods after reading what you have posted, I'm doing it for my own experience as I'm planning to finally make the move to vB after having the license for more than a year now lol (been running WBB2.x for ages)

hope that you guys to continue on posting more good stuff :)

rossco_2005
17 Nov 2009, 23:45
Very nice job.
I wasn't aware of pre-registering. :)
Thanks.

cellarius
18 Nov 2009, 03:11
Not a problem!

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Another note; on multidimensional arrays...
Suppose you have a nested / multidimensional array set, like:

// Array declaration & assignment

$multiDim = array(
'level1' => array(
'foo' => 'one',
'bar' => 'two',
'baz' => 'three',
'qux' => 'four'
),
'test' => 'testval'
);

// Variable Registration

vB_Template::preRegister(
'header', array('multiDim' => $multiDim)
);
You can chain the array 'keys' like in the second example:

{vb:raw multiDim.test} <!-- Output: testval -->
{vb:raw multiDim.level1.baz} <!-- Output: three -->
I have extended my example to provide for multidimensional arrays. Thanks for pointing this out :)

testebr
18 Nov 2009, 11:52
Can you give us a simple example of how to insert code to footer without fech from other template?

cellarius
18 Nov 2009, 13:00
Try to insert $my_insertvar
vB_Template::preRegister('footer',array('my_insertvar ' => $my_insertvar));
and call {vb:raw my_insertvar}.

testebr
18 Nov 2009, 20:17
hi cellarius, I don't want to call the var manually, I just want to inject code like my old example for 3.x:

hook: parse_templates

code: $vbulletin->templatecache['footer'] .= 'text added to footer';

Capiche?

cellarius
18 Nov 2009, 20:23
Nope, that does not work. You would need to do a str_replace on something you know is there.

testebr
18 Nov 2009, 21:54
I figure out how to solve it:

hook: process_templates_complete

code: $footer .= 'text added to footer';

No idea if was the best solution, but that worked very well.

cellarius
18 Nov 2009, 22:13
hook: process_templates_complete

code: $footer .= 'text added to footer';


Indeed, you can manipulate the already rendered template doing this. Also possible is str_replace:
$search = "Terms of Service";
$replace = "Terms of Cooking Noodles";
$footer = str_replace($search,$replace,$footer);Although this is a somewhat bad example, since "Terms of Service" is a phrase, of course, and will vary by language. Always make sure you use strings for replacement that are always present.

106372

Using str_replace, you can also add stuff in the middle of the template like so:
$search = "Terms of Service";
$replace = " and Terms of Cooking Noodles";
$footer = str_replace($search,$search.$replace,$footer);

106374

David Regimbal
19 Nov 2009, 21:26
Hi,

I'm trying to add something that requires PHP under the navbar. Back in vb 3.8.x I just used plugins for this. But, I'm not sure which hook to use if I want to display something under the navbar.

cellarius
20 Nov 2009, 12:19
@David: This is not related to the topic of this article. You should open your own thread on this..


Also, I just added the bonus track about template caching.

ragtek
20 Nov 2009, 17:02
@David: This is not related to the topic of this article. You should open your own thread on this..


Also, I just added the bonus track about template caching.

Sure?
It's $cache[] = 'xxx'; and not $globaltemplate now;) ;)

cellarius
20 Nov 2009, 17:10
Ah, damn, of course you're right. I had my example code for vB3 and the one I was about to change for vB4 side by side and then obviously copied/pasted the wrong one. Stupid me :)

ragtek
20 Nov 2009, 17:19
Ah, damn, of course you're right. I had my example code for vB3 and the one I was about to change for vB4 side by side and then obviously copied/pasted the wrong one. Stupid me :)

Yea, i know.
I made the mistake in all my add-ons on porting them to vB4:D

EidolonAH
22 Nov 2009, 02:15
Thanks for the "cache your templates" info, I made use of this info after making my own Terms of Service and Privacy custom pages, very helpful, thank you.:up:

Zaiaku
27 Nov 2009, 23:13
Indeed, you can manipulate the already rendered template doing this. Also possible is str_replace:
$search = "Terms of Service";
$replace = "Terms of Cooking Noodles";
$footer = str_replace($search,$replace,$footer);Although this is a somewhat bad example, since "Terms of Service" is a phrase, of course, and will vary by language. Always make sure you use strings for replacement that are always present.

106372

Using str_replace, you can also add stuff in the middle of the template like so:
$search = "Terms of Service";
$replace = " and Terms of Cooking Noodles";
$footer = str_replace($search,$search.$replace,$footer);

Also can this be used on variables? ex: {vb:raw variable}

106374

OK I'm trying to do the same thing but on showthread, from this example is $footer a var already being used of is this an additional variable made up int he plugin? Right now I'm using $vbulletin->templatecache['postbit'] with the <hookname>process_templates_complete, should this something diffrent?

<hookname>showthread_query</hookname>
$vbulletin->templatecache['postbit'] = str_replace($find, $replace, $vbulletin->templatecache['postbit']);

Also can this be used on variables? ex: {vb:raw variable}

jlevi
01 Dec 2009, 20:42
This isn't working for me. I'm probably doing something wrong, but at the moment I have a custom php page (I created following another tutorial elsewhere) that is calling a custom template.

The code for the php page:
<?php

// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################

define('THIS_SCRIPT', 'test');
define('CSRF_PROTECTION', true);
// change this depending on your filename

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array();

// get special data templates from the datastore
$specialtemplates = array();

// pre-cache templates used by all actions
$globaltemplates = array('TESTPAGE',
);

// pre-cache templates used by specific actions
$actiontemplates = array();

// ######################### REQUIRE BACK-END ############################
require_once('./global.php');

// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################

$navbits = construct_navbits(array('' => 'Test Page'));
$navbar = render_navbar_template($navbits);

// ###### YOUR CUSTOM CODE GOES HERE #####
$pagetitle = 'My Page Title';

// ###### NOW YOUR TEMPLATE IS BEING RENDERED ######

$templater = vB_Template::create('TESTPAGE');
$templater->register_page_templates();
$templater->register('navbar', $navbar);
$templater->register('pagetitle', 'Test Page');
print_output($templater->render());

?>


And the HTML template (called TESTPAGE):
{vb:stylevar htmldoctype}
<html xmlns="http://www.w3.org/1999/xhtml" dir="{vb:stylevar textdirection}" lang="{vb:stylevar languagecode}" id="vbulletin_html">
<head>
<title>{vb:raw vboptions.bbtitle}</title>
{vb:raw headinclude}
</head>
<body>

{vb:raw header}

{vb:raw navbar}

<div id="pagetitle">
<h1>{vb:raw pagetitle}</h1>
</div>

<h2 class="blockhead">Title</h2>
<div class="blockbody">
<div class="blockrow">
Text
</div>
</div>

{vb:raw footer}
</body>
</html>

And the plugin in global_start:
$templater = vB_Template::create('TESTPAGE');
print_output($templater->render());


Where have I gone wrong? I've spent a good half an hour going through the tutorial and trying various things but can't seem to get it working. It always makes the whole site blank, but if I call another template (e.g. contactus instead of TESTPAGE) it works fine, so the problem seems to lie with the plugin.

Any help greatly appreciated - thanks in advance :)

Seven Skins
01 Dec 2009, 20:47
In the plugin change "THEMEFLARE" to "TESTPAGE" ....

jlevi
01 Dec 2009, 21:06
In the plugin change "THEMEFLARE" to "TESTPAGE" ....

Oops... that's not the problem, I've checked and it is "TESTPAGE", just a typing error on my part. Thanks for helping :)

Edit: I've updated my original post.

sebz2009
02 Dec 2009, 05:41
I seemed to have gotten it to work. :D

Downloads.php
<?php

// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE & ~8192);

// Define the unique name for this script
define('THIS_SCRIPT', 'Downloads');

// List of templates used on this page
$globaltemplates = array(
'DOWNLOADS_SHELL'
);

// List of action related templates used on this page
$actiontemplates = array();

require_once('./global.php');

// Navbar location
$navbits = construct_navbits(array('' => 'Downloads'));
$navbar = render_navbar_template($navbits);

// HTML stuff
$HTML = "<INSERT WHATEVER CODE YOU WANT>";

// Fetch and parse templates
$templater = vB_Template::create('DOWNLOADS_SHELL');
$templater->register_page_templates();
$templater->register('headinclude', $headinclude);
$templater->register('navbar', $navbar);
$templater->register('header', $header);
$templater->register('HTML', $HTML);
$templater->register('footer', $footer);
print_output($templater->render());

?>


DOWNLOADS_SHELL

{vb:raw headinclude}

{vb:raw header}

{vb:raw navbar}

{vb:raw HTML}

{vb:raw footer}

</body>
</html>

gurler
06 Dec 2009, 23:04
thank you very much..

CrazyProgrammer
07 Dec 2009, 00:55
eval( '$comment_boxes .= "' . fetch_template('App_Question_box') . '";' ) ;
i have this how can make this into the new vbulletin format im not understanding this :(

Lynne
07 Dec 2009, 05:19
eval( '$comment_boxes .= "' . fetch_template('App_Question_box') . '";' ) ;i have this how can make this into the new vbulletin format im not understanding this :(

You're gonna translate into something like this, but only you know the variables that will need to be registered:
/* render template and register variables */
$templater = vB_Template::create('App_Question_box');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$comment_boxes .= $templater->render();

sebz2009
10 Dec 2009, 01:26
Alright, now I'm a bit stumped.
I cant seem to get the title of the page to register and it the pages don't work with subdomains.

Anyone got a clue?

cellarius
10 Dec 2009, 08:15
Alright, now I'm a bit stumped.
I cant seem to get the title of the page to register and it the pages don't work with subdomains.

Anyone got a clue?
I'm not sure I understand your problem. From what I try to gather I am also not sure if you're asking anything that is in correspondence with the article.

sebz2009
10 Dec 2009, 15:24
Alright, my bad. I got the title to work.

The bit about the subdomains does relate back to this.

I've made a custom page using this How-To.
When I load the page in the directory that global.php is in (the forum root directory) it loads absolutely fine.

What I'm trying to do is made this template appear in a sub domain (stats.example.com) rather than being in the root (example.com) where the forums live.

When I try running the code from the sub domain, it comes up and says that it doesn't know where "./global.php" is.
I change this to be "http://example.com/global.php".

That's fine, but then I get another error saying that it then can't find another .php file, etc, etc.

I'm just trying to figure out how I can get my custom page to load on a sub domain.

cellarius
10 Dec 2009, 15:32
Ahm, just like I suspected.
I've made a custom page using this How-To.
This tutorial is not about making custom pages, and has nothing to do with your problem. This one is (http://www.vbulletin.org/forum/showthread.php?t=229194).

Lynne
10 Dec 2009, 15:53
Ahm, just like I suspected.

This tutorial is not about making custom pages, and has nothing to do with your problem. This one is (http://www.vbulletin.org/forum/showthread.php?t=229194).
Actually, since he mentions global.php, I suspect it is actually this one (http://www.vbulletin.org/forum/showthread.php?t=228112).

Good morning, er, evening cellarius! :)

cellarius
10 Dec 2009, 17:06
Actually, since he mentions global.php, I suspect it is actually this one (http://www.vbulletin.org/forum/showthread.php?t=228112).
Darn, your right of course - and obviously there's more than one person who should read thread titles more carefully :D

Good morning, er, evening cellarius! :)
And to you, Lynne - whatever suits our needs :)

Nuss
13 Dec 2009, 01:38
Please i need a little of help, i can't get this working..!!

I created a template called: contenedor_de_foro
So i only write "Hi" inside it.

I want to get "Hi" in my Header template so i made a plugin on global_start and put:


$templater = vB_Template::create('contenedor_de_foro');
$templater->register_page_templates();
$contenedor = $templater->render();
vB_Template::preRegister('header', $contenedor);

Later went to header template and write {vb:raw contenedor} at the first line, and cant get "Hi" (get nothing)

James Birkett
13 Dec 2009, 21:47
Do we need to register stylevars as well?

MaestroX
14 Dec 2009, 03:29
Hi cellarius,

Thanks for the great article :)

I running into a bit of a problem, I can see the solution right in front of me but for some reason can't quite get it. Bassically I'm making a plugin so I have the breadcrumbs in the header.

This is what I've got so far setup on the parse_templates hook:

$templater = vB_Template::create('breadcrumbs');
vB_Template::preRegister(
'breadcrumbs', array('navbits'=> $navbits)
);
$templatevalues['breadcrumbs'] = $templater->render();
vB_Template::preRegister('header', $templatevalues);

The template is called into the header template but for some reason the navbit array doesn't seem to be working?

Thanks

nubian
21 Dec 2009, 04:38
Thank you cellarius for this!
I've even printed this out and read this even while sitting on the throne quite a few times.

I got some of the options working for a custom about us page.
The option to - Output template directly - custom pages works just great for VB4.

The option to - Save into a variable for later use in custom template works only after noticing an error in this code.
In VB4 This resulted in a blank white page.$templater = vB_Template::create('my_other_template');
$templater->register('my_template_rendered', $my_template_rendered);
print_output($templater->render()); I used this to fix it...
$templater = vB_Template::create('my_other_template');
$templater->register('my_template_rendered', $mytemplate_rendered);
print_output($templater->render()); Then sure enough it worked!

Then option to - Save into an array and preregister to use in an existing/stock template.
Unfortunately I was unable to get this working.
I could not locate the template hook "forumhome_wgo_pos2" in VB4.

As for Caching Templates, I didn't see any templates in red on because it this doesn't work on server that is ran locally.
I've managed to get this working on an actual server.
EDIT: I does work locally in my testing environment, I added...
$config['Misc']['debug'] = true;to the wrong config.php file. :o

Thanks for this write up, It helped me quite a bit in understanding more and more about VB.

cellarius
21 Dec 2009, 06:21
Thank you cellarius for this!
I've even printed this out and read this even while sitting on the throne quite a few times.
Too much information :D

The option to - Save into a variable for later use in custom template works only after noticing an error in this code.
There's no error in the code. You just changed the name of ine variable, and of course you are free to do so. The variables are just examples, you can name them whatever you want.


Then option to - Save into an array and preregister to use in an existing/stock template.
Unfortunately I was unable to get this working.
I could not locate the template hook "forumhome_wgo_pos2" in VB4.
The hook is there, if not, you have customized your FORUMHOME template and removed it. Anyway, this also is just an example; it works the same with any given template hook. Plus, I don't know why you think this belongs to the section where I write about preregistering - if you use a template hook, you don't need to preregister.

nubian
21 Dec 2009, 08:19
Too much information :D
It was a lot better than reading video game manuals. :)

There's no error in the code. You just changed the name of ine variable, and of course you are free to do so. The variables are just examples, you can name them whatever you want.
Yes, I'm aware of changing the variables to anything I want.
At first I was using your example to familiarize myself on how things work.
$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$mytemplate_rendered = $templater->render();

$templater = vB_Template::create('my_other_template');
$templater->register('my_template_rendered', $my_template_rendered);
print_output($templater->render());
The code above gave me a blank page because the var $mytemplate_rendered = $templater->render();
did not match second argument in the register function.
$templater->register('my_template_rendered', $my_template_rendered);

So I changed this:
$templater->register('my_template_rendered', $my_template_rendered);
to:
$templater->register('my_template_rendered', $mytemplate_rendered);

And everything worked fine.

The hook is there, if not, you have customized your FORUMHOME template and removed it. Anyway, this also is just an example; it works the same with any given template hook. Plus, I don't know why you think this belongs to the section where I write about preregistering - if you use a template hook, you don't need to preregister.

Pardon my ignorance since I'm still in developing stages of learning the functionality of how vb operates.
My guess is that I'm not fully understanding this particular option.
I've tried this on a clean install and was unable to locate this hook or maybe I'm just looking in the wrong place for it.
Additional guidance will very much be appreciated if you don't mind?

As for your last statement, I didn't not combine all of these options into one.
I created separate custom pages for each option just to see the results of each option listed.
The only one I had difficult understanding was the template hook option.

CypherSTL
24 Dec 2009, 18:20
Alright. I can get it to display just straight templates, that used to use just eval('print_output')...........

How would I go about displaying this:
eval('$userslist .= ", ' . fetch_template('userslist_bit') . '";');

Lynne
24 Dec 2009, 18:41
Alright. I can get it to display just straight templates, that used to use just eval('print_output')...........

How would I go about displaying this:
eval('$userslist .= ", ' . fetch_template('userslist_bit') . '";');
$newTemplate = vB_Template::create('userslist_bit');
$newTemplate->register('variable1', $variable1);
$newTemplate->register('variable2', $variable2);
$userslist .= $newTemplate->render();

CypherSTL
28 Dec 2009, 19:46
I still cannot figure out how in the heck to work this new template system.


eval('$awarduserslist .= ", ' . fetch_template('awards_awardusers_bit') . '";');

Works flawlessly. No errors.

However

$displayTemplate = vB_Template::create('awards_awardusers_bit');
$awarduserslist .= $displayTemplate->render();

Displays absolutely NOTHING.

scarex
29 Dec 2009, 12:46
Thanks for this guide, at the beginning I was totally confused about this new system.

On the other hand, is there a system to preregister a var in all templates with a single call?

IR15H
30 Dec 2009, 01:51
Thanks for the guide :)

rbc
31 Dec 2009, 14:52
Introduction
~snip~


@ cellarius (http://www.vbulletin.org/forum/member.php?u=109187)

Absolutly a great introduction how things now working on VB4.
It answere`s many questions to me now.

I just wanne thank you cellarius (http://www.vbulletin.org/forum/member.php?u=109187) for this.

btw. many thanks to Lynne (http://www.vbulletin.org/forum/member.php?u=65230) who also allways help out.

i`m absolutly new to stuff like "vb" or "php" but with your "helping
hand`s" alot of work is possible to do for me too.

Sorry about my englisch, its not "my one (http://de.wikipedia.org/wiki/Schweiz)" :)

Thanks again an enjoy the hollydays ...... if there some ........

NLP-er
06 Jan 2010, 02:32
I have question:
How to change content of existing template inside of plugin?

I'm remaking my mod for vB4. I'm adding there flags to header of footer. In vB3 version I simply change insides of template using templatecache. I.e.:

$vbulletin->templatecache['footer'] .= 'ADDITIONAL TEXT IN FOOTER';


I was using it in global_start hook, but it doesn't work anymore - $vbulletin->templatecache['footer'] is empty and have no impact on footer.

How to change this line of code to make it working in vB4?

EDIT:
Ok - I already found it here :) Now check if its working :P

--------------- Added 1262746169 at 1262746169 ---------------

Other question:
In vB3 my mod have possibility to put additional data in custom place - so user just manually adds variable into required template and he has flags where he put it. How to do this in vB4 where variables have to be preregistered????...

--------------- Added 1262746545 at 1262746545 ---------------

I figure out how to solve it:

hook: process_templates_complete

code: $footer .= 'text added to footer';

No idea if was the best solution, but that worked very well.

This will work only for few templates. The question is how to make it work for any template like with $vbulletin->templatecache solution in vB3.

Also this solution is working on already parsed template - I need fresh one, not parsed yet. Anyone have idea how to do that?

EDIT
Ok I have it :) need to use hook parse_templates

Sarcoth
07 Jan 2010, 19:22
Awesome guide. It has helped me move forward a bit, but I still don't have it all down yet. If anyone has this down pat, I'd be interested in some more tutorials that show old 3.x code and then below shows the 4.x code. This way I can test myself and see how well I have it down.

In the meantime though, is the new rendering needed for redirects? For example:
$vbulletin->url = "misc.php?do=editform&fid=$fid";
eval(print_standard_redirect('redirect_insertform', true));

I tried the following:
$templater = vB_Template::create('redirect_insertform');
$templater->register_page_templates();
$templater->register('redirect', $vbulletin->url);
print_standard_redirect($templater->render());

That didn't work though, it seems to be cutting off everything after misc.php. Maybe I need to register the $fid?

cellarius
07 Jan 2010, 21:28
No, standard redirects and errors still work the old way. If you want to know something like that, just look one up in the original vB4 php files.

Abe Babe
12 Jan 2010, 08:26
I have a template that I need to insert into multiple pre-existing templates (I add some additional graphics/formatting to the header and footer of most tables ... and my CSS skills aren't good enough to achieve what I'm trying to do through CSS alone, so I need to add old HTML table coding). I do it this way so that if I want to make changes, I don't have to change lots of different templates. After a bit of struggling, I have managed to get the following code running.

$templater = vB_Template::create('layout_start');
$templater->register('my_var', $my_var);
$templatevalues['start_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);


I have two questions. Is there any way to preRegister for more than one pre-existing template (or a global registration), or do I have to create Plugins for every page I want to add this to (*groan*)? And what is the best hook to have this on. I am currently using 'parse_templates'.

The other unusual thing I'm finding happening is if I include my template in postbit_legacy, it will show on the first post, but not on the posts after that.

Thanks in advance...

cellarius
13 Jan 2010, 03:16
$templater = vB_Template::create('layout_start');
$templater->register('my_var', $my_var);
$templatevalues['start_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues); I have two questions. Is there any way to preRegister for more than one pre-existing template (or a global registration), or do I have to create Plugins for every page I want to add this to (*groan*)?
Just calling the preregister method as often as you need it might not work in this case, since the method clears the variable. So trying to simply preregister it again might not be feasible. Anyway, try this:
$templater = vB_Template::create('layout_start');
$templater->register('my_var', $my_var);
$templatevalues['start_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);
vB_Template::preRegister('SHOWTHREAD', $templatevalues);
vB_Template::preRegister('FORUMDISPLAY', $templatevalues);
If this does not work, try something like this:
$templater = vB_Template::create('layout_start');
$templater->register('my_var', $my_var);
$start_insertvar = $templater->render();
$templatevalues['start_insertvar'] = $start_insertvar;
vB_Template::preRegister('FORUMHOME', $templatevalues);
$templatevalues['start_insertvar'] = $start_insertvar;
vB_Template::preRegister('SHOWTHREAD', $templatevalues);
$templatevalues['start_insertvar'] = $start_insertvar;
vB_Template::preRegister('FORUMDISPLAY', $templatevalues);
Of course, if you have really many templates, it might be more elegant to solve this with an array an a nice loop.
And what is the best hook to have this on. I am currently using 'parse_templates'.Seems fine to me.

Ted S
16 Jan 2010, 19:19
...

psypher
18 Jan 2010, 22:13
nvm figured it out

mokujin
19 Jan 2010, 22:45
I have read all posts and dont know how to call 3 templates in one page.

I have this code:

if ($_REQUEST['do'] == 'page1')
{
$templater = vB_Template::create('temp_page1');

/*
how can I fetch another template here?
in vb3: eval('$pagebit .= "' . fetch_template('page_bit') . '";'); ???

*/

$mypage .= $templater->render();
}
// called 2 templates 'temp_page1' and 'temp_home' OK, and what 'page_bit'?

$templater = vB_Template::create('temp_home');
$templater->register_page_templates();
$templater->register('mypage', $mypage);
$templater->register('navbar', $navbar);
$templater->register('pagetitle', $pagetitle);
print_output($templater->render());

derfelix
21 Jan 2010, 06:04
I would fetch it before...

if ($_REQUEST['do'] == 'page1')
{

$templater = vB_Template::create('page_bit');

$mypage_bit .= $templater->render();

$templater = vB_Template::create('temp_page1');
$templater->register('mypage_bit', $mypage_bit);
$mypage = $templater->render();
}


$templater = vB_Template::create('temp_home');
$templater->register_page_templates();
$templater->register('mypage', $mypage);
$templater->register('navbar', $navbar);
$templater->register('pagetitle', $pagetitle);
print_output($templater->render());


F.

ChopSuey
23 Jan 2010, 00:29
Thanks for this, hopefully i'll be able to know what to do.

TheSupportForum
25 Jan 2010, 07:56
does anyone know how i can insert this into a template using plugin manager
to be placed in header


function bb2_insert_head() {
global $bb2_javascript;
echo $bb2_javascript;
}

OcR Envy
25 Jan 2010, 16:30
n/m I figured I was missing $templater->render();

moonray
09 Feb 2010, 18:21
I am not much of a coder at all, and hence need your help big time.

I want to call a simple php file to be placed just under the navbar. So, I created a plugin:
Product: vBulletin
Title: Insert Simple PHP
Execution order: 5 (it was default)
Hook Location: global_start
PHP code:
ob_start();
include('simple.php');
$insert_simple_php = ob_get_contents();
ob_end_clean();
Plugin is active: Yes

Now, I went to the NAVBAR template and inserted
{vb:raw insert_simple_php}
just under the code
{vb:raw ad_location.global_below_navbar}

Questions:
* Where does the 'register/pre-register' come?
* What is the exact change I need to make here?

Thanks for your help!

FatalBreeze
17 Feb 2010, 18:29
Great article!
but i have a problem.
I have a template which i want to show inside another template, and it seems to work with every template except for the header.
This is the plugin i used:

$templateH = vB_Template::create('TopPanel')->render();
vB_Template::preRegister('header', array('TopPanel' => $templateH));
$TL = vB_Template::create('TopPanel')->render();
vB_Template::preRegister('vbcms_page', array('TopPanel' => $TL));
$TL2 = vB_Template::create('BarH')->render();
vB_Template::preRegister('vbcms_page', array('BarT' => $TL2));


the hook location is: process_templates_complete.
of course i have a template called TopPanel which i created, and it works great in vbcms_page for example but not in header.
Do you have an idea why is that?

Thanks in advance.

cellarius
18 Feb 2010, 07:45
As the name suggests, the hook you use is called when vB-internal template processing is already completed. No use in preregistering templates then anymore. Since that hook did not exist in 4.0.1 as far as I can see, you're using 4.0.2. Another hook that got added in 4.02 is template_register_var, and that would be the right one to use.

cellarius
23 Feb 2010, 09:19
I am not much of a coder at all, and hence need your help big time.

I want to call a simple php file to be placed just under the navbar. So, I created a plugin:
Product: vBulletin
Title: Insert Simple PHP
Execution order: 5 (it was default)
Hook Location: global_start
PHP code:
ob_start();
include('simple.php');
$insert_simple_php = ob_get_contents();
ob_end_clean();Plugin is active: Yes

Now, I went to the NAVBAR template and inserted
{vb:raw insert_simple_php}just under the code
{vb:raw ad_location.global_below_navbar}Questions:
* Where does the 'register/pre-register' come?
* What is the exact change I need to make here?

Thanks for your help!

Try this in the plugin:
ob_start();
include('simple.php');
$templatevalues['insert_simple_php'] = ob_get_contents();
ob_end_clean();
vB_Template::preRegister('navbar', $templatevalues);

Muller2
23 Feb 2010, 23:43
cellarius & moonray - you are both stars!!! :D

Thanks you!

Al

moonray
24 Feb 2010, 02:41
FINAL WORKING CODE:

Product: vBulletin
Title: Insert Simple PHP
Execution order: 5
Hook Location: global_start
PHP code:
ob_start();
include('simple.php');
$simple_php = ob_get_contents();
ob_end_clean();

vB_Template::preRegister('navbar',array('simple_php' => $simple_php));
Plugin is active: Yes

Now, go to the NAVBAR template and insert
{vb:raw insert_simple_php}
just under the code
{vb:raw ad_location.global_below_navbar}

TalkVirginia
25 Feb 2010, 14:12
I'm hoping someone can help me.. I'm having trouble displaying Openx Ads in various locations. For example in the header template.

This is the php code that Openx generates:


//<!--/* OpenX Local Mode Tag v2.8.4 */-->

// The MAX_PATH below should point to the base of your OpenX installation
define('MAX_PATH', 'path/to/openx');

if (@include_once(MAX_PATH . '/www/delivery/alocal.php'))
{

if (!isset($phpAds_context))
{
$phpAds_context = array();
}

$phpAds_raw = view_local('', 1, 0, 0, '_blank', $forumid, '0', $phpAds_context, '');

echo $phpAds_raw[html];
}



This is the code I'm trying to use:



//<!--/* OpenX Local Mode Tag v2.8.4 */-->

// The MAX_PATH below should point to the base of your OpenX installation
define('MAX_PATH', '/path/to/openx');

if (@include_once(MAX_PATH . '/www/delivery/alocal.php'))
{
ob_start();

if (!isset($phpAds_context))
{
$phpAds_context = array();
}

$phpAds_raw = view_local('', 1, 0, 0, '_blank', $forumid, '0', $phpAds_context, '');

$templater = vB_Template::create('ad_global_header2');

$templater->register('phpAds_raw', $phpAds_raw);

$templatevalues['phpAds_raw'] = ob_get_contents();

ob_end_clean();

vB_Template::preRegister('header', $templatevalues);

}

TalkVirginia
26 Feb 2010, 17:25
No comments on my last post?

wajones
28 Feb 2010, 10:02
This is what I'm using.

ob_start();

if (include('ads/phpadsnew.inc.php')) {
if (!isset($phpAds_context)) $phpAds_context = array();
$sponsor = view_raw ('6', 7, '_blank', '', '0', $phpAds_context);

}

ob_end_clean();
vB_Template::preRegister('navbar',array(
'sponsor' => $sponsor));

TalkVirginia
28 Feb 2010, 18:24
Thank you very much WAJones!! That works great! :D :up: :up: :up:

masterross
01 Mar 2010, 21:49
Guys help me to update this hack to vB 4
http://www.vbulletin.org/forum/misc.php?do=producthelp&pid=guests_first_post_only_37

I cant show the message "register...." to guests:

if ($show['guest'] AND $forum['gfpo_enabled'])
{
eval('$postbit = "' . fetch_template('postbit_gfpo') . '";');
eval('$postbits .= "' . fetch_template('postbit_wrapper') . '";');
}

Michael Biddle
01 Mar 2010, 23:03
Great article!

I have a question. In vB3, you could do this:

$template_hook['navbar_buttons_left'] .= '<td class="vbmenu_control"><a href="index.php">Home Page</a></td>';

Is it possible to just have the html in the plugin, or does it need to be in its own template in vb4?

masterross
01 Mar 2010, 23:49
Great article!

I have a question. In vB3, you could do this:

$template_hook['navbar_buttons_left'] .= '<td class=&quot;vbmenu_control&quot;><a href=&quot;index.php&quot;>Home Page</a></td>';Is it possible to just have the html in the plugin, or does it need to be in its own template in vb4?

It's absolutely the same in vB 4 only hooks are different.

TalkVirginia
03 Mar 2010, 23:34
I'm trying to append some text to the end of the footer.. in a plugin.. but I'm totally lost.

How do I get the footer out of the cache to append some text to it?

masterross
03 Mar 2010, 23:45
I'm trying to append some text to the end of the footer.. in a plugin.. but I'm totally lost.

How do I get the footer out of the cache to append some text to it?

Why dont you use ad_footer_end hook?

TalkVirginia
04 Mar 2010, 11:44
I figure out how to solve it:

hook: process_templates_complete

code: $footer .= 'text added to footer';

No idea if was the best solution, but that worked very well.

Indeed, you can manipulate the already rendered template doing this. Also possible is str_replace:
$search = "Terms of Service";
$replace = "Terms of Cooking Noodles";
$footer = str_replace($search,$replace,$footer);Although this is a somewhat bad example, since "Terms of Service" is a phrase, of course, and will vary by language. Always make sure you use strings for replacement that are always present.

106372

Using str_replace, you can also add stuff in the middle of the template like so:
$search = "Terms of Service";
$replace = " and Terms of Cooking Noodles";
$footer = str_replace($search,$search.$replace,$footer);

106374

Testbr and Cellarius - Thank you so much! I finally found your post which solved my issue. After seeing it, it's so simple I felt like smacking myself.. LOL :eek: :facepalm:

abomohammad
06 Mar 2010, 19:21
Hi , I need for help

I created a template called: my_template
and write "Hi" inside it.

I want to get "Hi" in my FORUMHOME template
so i made a plugin on global_start and put:

$templater = vB_Template::create('my_template');
$templater->register('my_var', $my_var);
$templater->render();

then i post {vb:raw my_var} in FORUMHOME
but nothing apper to me

How to get my_template content in FORUMHOME or other template ???

masterross
06 Mar 2010, 21:10
Hi , I need for help

I created a template called: my_template
and write "Hi" inside it.

I want to get "Hi" in my FORUMHOME template
so i made a plugin on global_start and put:

$templater = vB_Template::create('my_template');
$templater->register('my_var', $my_var);
$templater->render(); then i post {vb:raw my_var} in FORUMHOME
but nothing apper to me

How to get my_template content in FORUMHOME or other template ???

Did you read the fist post in the thread?

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$templatevalues['my_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);

abomohammad
07 Mar 2010, 00:51
Did you read the fist post in the thread?

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$templatevalues['my_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);

Yes, I read it, but do not work :confused:

Joseph Witchard
07 Mar 2010, 04:43
I apologize for sounding so helpless, but what exactly do you do with templates, and where do you even go to put in the PHP code for them? I opened this article thinking it was about skins. I'll continue to look for a thread about skins, but all this sounds like it's also important on modifying vBulletin to suit your needs, so that's why I'm posting here.

masterross
07 Mar 2010, 08:29
Yes, I read it, but do not work :confused:
you also need to use right hook location!
For FORUMNOME probably will be forumhome_start or forumhome_complete


Regards!

TalkVirginia
07 Mar 2010, 13:53
Is it possible to use a custom template and render it into a variable then use that variable in sending HTML email?

I'm trying to use the following PHP code:



$templater = vB_Template::create('mycustom_template');
$templater->register('username', $username);
$templater->register('bbtitle', $bbtitle);
$templater->register('homeurl', $homeurl);
$templater->register('forumurl', $forumurl);
$templater->register('hometitle', $hometitle);
$message = $templater->render();



I have the following variables defined in my template:



{vb:raw username}
{vb:raw bbtitle}
{vb:raw homeurl}
{vb:raw forumurl}
{vb:raw hometitle}

princeedward
12 Mar 2010, 22:47
thanks for this and hope that someday i can do this too alone and well enough of my own without error...but it's not quite easy at all to understand...just to be honest....:p

well i was about experimenting to show the Current Activity of the Currently Active Members above inside WGO BOX (by mouse hover to the username)....by adding the red code below

<li> {vb:stylevar dirmark}<a class="username" href="{vb:link member, {vb:raw loggedin}}" title="{vb:rawphrase current_activity} {vb:raw loggedin.action} {vb:raw loggedin.where}
">{vb:raw loggedin.musername}</a>{vb:raw loggedin.invisiblemark}{vb:raw loggedin.buddymark}</li>


...to the vbdefault template of forumhome_loggedinuser but it didn't quite well and good even i tried to preregistered those variables....well i'm not sure too if i did it right or not...


vB_Template::preRegister('FORUMHOME',array(
'loggedin.action ' => $loggedin.action));
'loggedin.where ' => $loggedin.where));

can anyone guide me on this please...
thanks and best regards to all

:o

cellarius
12 Mar 2010, 23:38
$loggedin.action or $loggedin.where are not valid PHP variables. I do not think that this is just a registering problem. You should probably open your own thread in the forums and explain exactly what and how you are trying to do.

grecostimpy
13 Mar 2010, 02:48
This is a great thread and I know I'm on the right track.

I am trying to add a custom profile field to the memberaction_dropdown template.

{vb:raw post.field5}

How would I register this to work in the memberaction_dropdown? It works on postbit (because I'm assuming it is registered)

Thanks again for a great write-up!

princeedward
13 Mar 2010, 07:24
$loggedin.action or $loggedin.where are not valid PHP variables. I do not think that this is just a registering problem. You should probably open your own thread in the forums and explain exactly what and how you are trying to do.hmmm...if you dont mind mate lookin on this THREAD (http://www.vbulletin.org/forum/showthread.php?t=238238) please...it might give you slight idea what i'm trying to do...and hope you can throw me some hint and help...

thanks anyway for your time mate to reply on this...

best regards...

:p

gkaradagan
13 Mar 2010, 18:13
i want to do that some codes work in navbar template but same code dont work in header or navbar . for example how can i run vb:raw forum.title} in forumhome.lastpostinfo template ?

testbot
18 Mar 2010, 03:16
i'm a little confused on how to get my loops into the templates.

how would i get mypage.php:

while ($result = $db->fetch_array($results)){
$something .= $result['field1'];
$something2 .= $result['field2'];
}
$templater->register('something ', $something );


to show all looped values in mytemplate:

<ul>
START TO DISPLAY LOOPED DATA
<li>
{vb:raw something}
</li>
END TO DISPLAY LOOPED DATA
</ul>

LaCN
29 Mar 2010, 18:42
I've been trying like crazy... We need more turorials...


How do I get my variable $my_own_var in an existing template, like footer ?
How do I get an existing variable from an existing template (like $navbits from the navbar template) in an existing template like footer ?




@ vB staff: RTFM should be WTFM

masterross
29 Mar 2010, 23:19
I've been trying like crazy... We need more turorials...

How do I get my variable $my_own_var in an existing template, like footer ?use vB_Template::preRegister


How do I get an existing variable from an existing template (like $navbits from the navbar template) in an existing template like footer ?


@ vB staff: RTFM should be WTFM

you should register again existing vars:

$templater->register('navbits', $navbits);

LaCN
31 Mar 2010, 14:08
Thanks a bunch for the reply :) :)

use vB_Template::preRegister
Would this be needed to be doing in the hook location where it starts creating the footer ?
And in the case of the footer template, which has no hook-location, which hook location is best used ?

you should register again existing vars:

$templater->register('navbits', $navbits);
If the creating of the template navbar was done before the footer, would I pre-register the $navbits using the the hook-location in the "navbits_complete" ?

And if the navbar template was built after the footer, in which hook-location would I need to pre-register the $navbits ?

Thanks !

derfelix
31 Mar 2010, 15:12
as far as I have seen, footer template is created at the moment any other template is done...

example:
if at the top of a file.. before you did any template stuff...
you do
echo $footer; exit;
you will get a blank page...
but if you do:
$templater = vB_Template::create('anytemplate')->render();
echo $footer; exit;
the footer template will show...
--> so just find a place before the first template is created...

Felix

pneo
31 Mar 2010, 21:49
Please can somebody help, I just can't figure out what I'm doing wrong.

I'm trying to add to FORUMHOME and I can't get the basic example working.

I've created a new plugin (hook: forumhome_start) with the following PHP code:

$my_var = 'abc';
$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templatevalues['my_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);


I've then added the following to the FORUMHOME template:


<p>{vb:raw my_insertvar}</p>



Am I right in expecting <p>abc</p> to appear in my forum home page source? Because I just get empty <p></p>, i.e. the variable doesn't exist.

I've tried different hook locations. I also tested the forumhome_start location by adding an "echo 'abc'; in the plugin php, and as expected "abc" appears right at the top of my forum home source.

What am I doing wrong? :S



EDIT!:: Apologies, missed this post: http://www.vbulletin.org/forum/showpost.php?p=1990021&postcount=72

masterross
31 Mar 2010, 23:04
As you wrote it you should use my_var first in template mytemplate.
Then when you use <p>{vb:raw my_insertvar}</p> in FORUMHOME all content from mytemplate will be appear.

Sadikb
07 Apr 2010, 12:34
Just wanted to thank Cellarius for this very useful article. Thanks Mate...

caciocode
02 May 2010, 16:47
Where exactly do I write this content? This part is quite complicated

ckgreenman
03 May 2010, 19:56
Hello, I hope someone can point in the right direction. I'm trying to port a mod to vb4 which has a number of templates. The php file contains a whole bunch of eval('$template .= "' . fetch_template('templatename') . '";'); lines. The mod uses a main template which then calls the other templates from within the main template using $template references to the other templates.

I've tried a number of different iterations form the first post but I can't get anything but the main template to render. How does one go about making something like this work?


thanks.

ckgreenman
04 May 2010, 20:32
nevermind. Turns out I had numerous typos.


Now I'm running into a different problem. I'm editing a (sub)template which is rendered in a variable in the php file and called using:
{vb:raw display_map}

The display_map template references a number of variables which are defined in the php script and populated with data pulled from the database. When I try to edit the template and use the {vb:raw variable} I'm unable to save the template due to the following error:
Warning: Invalid argument supplied for foreach() in [path]/includes/functions.php on line 3332

vBulletin Message
The following error occurred when attempting to evaluate this template:
%1$s
This is likely caused by a malformed conditional statement. It is highly recommended that you fix this error before continuing, but you may continue as-is if you wish.


Any suggestions where the problem might be? It doesn't seem to matter where I put the variable reference. If there is {vb:raw variable} in the template it won't save.

GameExploiters
07 May 2010, 22:22
Introduction

Starting with vB4, templates no longer get output using eval:
eval('$mytemplate = "' . fetch_template('mytemplate') . '";');is outdated.
What's more: Variables and arrays from plugins that are executed on a page no longer can automatically be accessed in the templates of that page. They need to be registered first.
.
Basic functionality to render templates and register all variables/arrays you want to use inside

/* Some Code, setting variables, (multidimensional) array */
$my_var = "abc";
$my_array = array(
'key1' => 'value1',
'key2' => array('
'key21' => 'value21',
'key22' => 'value22'
')
);

/* render template and register variables */
$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$templater->render();

The first line provides the template that is to be rendered, using the new vB_Template class (vB_Template::create). The method gets passed the name of the template as an argument.
The following two lines register a variable and an array that we want to use in our template. Arguments passed are 1. the name you want to use to access the variable, and 2. the variable from the code you want to register. You can register as many variables/arrays as you want. Just remember you have to register every variable and array that you want to use in your custom template in this way. If you don't register them, they will not be available.
The fourth line renders the template ($templater->render()). In the template you know will be able to use the registered variables/arrays in this way:
{vb:raw my_var}
{vb:raw my_array.key1}
{vb:raw my_array.key2.key21}Note the last one: multidimensional arrays are perfectly possible.
.
.
.
Now, with the result of the rendering we can do several things:
.
Output template directly - custom pages

$templater = vB_Template::create('mytemplate');
$templater->register_page_templates();
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
print_output($templater->render());This immediatly outputs the template. Use this if you have created your own page, for example.
Note the second line, which is special for this type of use:
$templater->register_page_templates();This auto-registers the page level templates header, footer and headinclude that you will use in the template of your custom page.
.
Use a template hook

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$template_hook[forumhome_wgo_pos2] .= $templater->render();The template will be shown using the choosen template hook (for example: $template_hook[forumhome_wgo_pos2]). See the dot before the = in the last line? The hook may be used by other modifications, too, so we don't want to overwrite it, but rather append our code to it, conserving everything that might already be there.
.
Save into a variable for later use in custom template

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$mytemplate_rendered = $templater->render();Now we have saved the rendered template into a variable. This variable in turn we can later on register in another template, if we want:
$templater = vB_Template::create('my_other_template');
$templater->register('my_template_rendered', $my_template_rendered);
print_output($templater->render());Again, inside my_other_template we now could call
{vb:raw my_template_rendered}If you're running the first template call inside a loop, you may want to use .= instead of = in the last line, so that the results of every loop get added instead of overwriting the existing. But that depends, of course.
.
Save into an array and preregister to use in an existing/stock template

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$templatevalues['my_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);

This is another, more flexible method to save the rendered template into a variable for future use in an already existing template. In this example, we want to show our own rendered template on forumhome.
Problem is: We have no direct way to register variables for already existing templates like FORUMHOME. It's created and rendered in the files, and we don't want to mess there.
To help with this, a new method was created for vB_Template class, called preRegister. Using this, we can pass our data to FORUMHOME before it is rendered. Note that the data needs to be saved into an array ($templatevalues['my_insertvar']), a simple variable will throw an error. In the last line the array is preregistered; you need to pass as arguments 1. the name of the existing template and 2. the array that contains the data. Again, this can be done for as many arrays as needed.
Of course, the preRegister functionality can be used for any kind of variables or arrays, no matter whether you have saved a rendered template (like in our example) into it or it contains just a simple boolean true/false statement. To access the data inside the template it was preregistered for use:
{vb:raw my_insertvar}Note: it is not {vb:raw templatevalues.my_insertvar}!

Essentially the same as what I put for preRegister would be the following two lines. They could replace the last two lines in the above php codebox:
$my_insertvar = $templater->render();
vB_Template::preRegister('FORUMHOME',array('my_insertvar ' => $my_insertvar));
Of course you could add further pairs to that array if you need to preregister more than one variable.
.
.
Bonus track: ...whatever you do, cache your templates!

Now you know how to get your templates on screen - once you succeeded in doing that, make sure to do it in a fast and ressource saving manner: make use of vB's template cache. To see whether your templates are cached or not, activate debug mode by adding $config['Misc']['debug'] = true;to your config.php (don't ever use that on your live site!). Among the debug info is a list of all templates called, and non-cached templates will show up in red.

To cache your templates, add a plugin at hook cache_templates with the following code:

// for a single template
$cache[] = 'mytemplate';

// for more than one templates in one step
$cache = array_merge((array)$cache,array(
'mytemplate',
'myothertemplate',
'mythirdtemplate'
));.
.
Hope this helps!
-cel

----
Addendum - There are now two blog posts on vb.com related to this topic:
http://www.vbulletin.com/forum/entry.php?2387-Pushing-your-variables-to-vBulletin-4-templates
http://www.vbulletin.com/forum/entry.php?2388-Using-custom-templates-within-your-own-vBulletin-4-based-files

I'm trying to render my Navbar template so i can add it to my custom templates and be able to change the navbar how would i go about doing this with this tutorial. I don't understand what I'm suppose to do exactly.

Dark_Wizard
25 Jun 2010, 19:13
nevermind. Turns out I had numerous typos.


Now I'm running into a different problem. I'm editing a (sub)template which is rendered in a variable in the php file and called using:
{vb:raw display_map}

The display_map template references a number of variables which are defined in the php script and populated with data pulled from the database. When I try to edit the template and use the {vb:raw variable} I'm unable to save the template due to the following error:
Warning: Invalid argument supplied for foreach() in [path]/includes/functions.php on line 3332

vBulletin Message
The following error occurred when attempting to evaluate this template:
%1$s
This is likely caused by a malformed conditional statement. It is highly recommended that you fix this error before continuing, but you may continue as-is if you wish.


Any suggestions where the problem might be? It doesn't seem to matter where I put the variable reference. If there is {vb:raw variable} in the template it won't save.
Chris...sent you a PM...

Bob

Frank T
01 Jul 2010, 21:06
I'm working to insert my own VAR into an existing template. I've seen the examples saying to use vb_Template::preRegister. However I have a catch...I'm using a cloned copy of an existing template. For example, I cloned the default style -- and created newStyle. Then within newStyle, I modified postbit_legacy and would like to display my own $var within the cloned copy of postbit_legacy.

Questions:
1. How to register/preRegister into a cloned template (newStyle->postbit_legacy).
2. How to properly use preRegister -- if that's what's needed. My data isn't an array, and preRegister only works with arrays.

cellarius
03 Jul 2010, 09:40
If you're creating a new style based on another one (in this case the default style), the template name is still postbit_legacy and the template itself still is template legacy. Doesn't matter at all.
If you're variable is not an array, make it an array. $templatevalues['myvariable'] = $myvariable.

SpeedyHire
20 Jul 2010, 09:23
Could you please point me in the right direction as to how I might add an extra field in newthread template, I was trying to do it automatically with the product install and I read here about using process_template hook and str_replace but Im still a little confused by it any help on this greatly appreciated.

cellarius
20 Jul 2010, 09:25
Please open your own thread for questions not directly related to this article.

SpeedyHire
20 Jul 2010, 16:14
It is related to this article? I'm asking how using what I found in this article i can do what others have clearly done since they said so in this thread. If you don't want to help me that's fine but since you helped others with there question to do with the footer I thought you might help me too silly me what was I thinking.

gopherhockey
26 Jul 2010, 14:24
oops, fixed it.

mustangcoupe69
30 Aug 2010, 00:42
I've tried following this example, but am having issues.

I am trying to get a custom template that was installed via an addon to show up in the header template.

My plugin (uses the global_start hook):
$templater = vB_Template::Create('vsa_paypal_donbar');
$templater->register('vsapaypal_donlist_cansee', $vsapaypal_donlist_cansee);
$templater->register('admincpdir', $admincpdir);
$templater->register('vsapp_donbar_goal', $vsapp_donbar_goal);
$templater->register('vsapp_donbar_total', $vsapp_donbar_total);
$templater->register('vsapp_donbar_done', $vsapp_donbar_done);
$templater->register('vsapp_donbar_left', $vsapp_donbar_left);
$templater->register('header', $header);

$vsapaypal_donbar = $templater->render();
vB_Template::preRegister('header',array('vsapaypal_donbar' => $vsapaypal_donbar));

Then my header template starts with:
{vb:raw vsapaypal_donbar}

What am I missing?

vicmx
02 Sep 2010, 07:08
To add a template in another with $template_hook add this plugin:

global $template_hook;
$newTemplate = vB_Template::create('YOUR_CUSTOM_TEMPLATE');
$template_hook['your_var'] .= $newTemplate->render();
Now just print in another template:
{vb:raw template_hook.your_var}For print in all pages, you can set {vb:raw template_hook.your_var} in navbar template for example.

valdet
07 Sep 2010, 10:35
Cellarius, this is an excellent article so I hope you may help me on my little issue. I read many threads and this article and I still cannot get aroudn to fix it.


In vB3 I had a simple plugin to display random banners on navbar template or parse_templates hook

$random_number = mt_rand(1, 5);

$random_banner[1] = '<img src="path/to/banner1.gif" alt="" border="0" />';
$random_banner[2] = '<img src="path/to/banner2.gif" alt="" border="0" />';
$random_banner[3] = '<img src="path/to/banner3.gif" alt="" border="0" />';
$random_banner[4] = '<img src="path/to/banner4.gif" alt="" border="0" />';
$random_banner[5] = '<img src="path/to/banner5.gif" alt="" border="0" />';

I just placed $random_banner[$random_number] anywhere in navbar and the banners would rotate on random basis.It was very simple and I would like to know how to make it work for vB4 as well.

I posted my problem in this thread too.
http://www.vbulletin.org/forum/showthread.php?t=249848

I hope you can help and thanks for your time.

Lynne
07 Sep 2010, 15:58
You need to then preregister the array $random_banner for use in the navbar. Something like:
vB_Template::preRegister('navbar', array('random_banner' => $random_banner));

valdet
08 Sep 2010, 08:53
Thank you very much Lynne,

I had to add a little bit more and actually change the plugin code to a simpler version.
Inside the plugin I had to create a third variable $new_banners and only pre-registered that variable within template and ran it through parse_templates hook

$random_number = mt_rand(1, 5);

$random_banner[1] = '<img src="path/to/banner1.gif" alt="" border="0" />';
$random_banner[2] = '<img src="path/to/banner2.gif" alt="" border="0" />';
$random_banner[3] = '<img src="path/to/banner3.gif" alt="" border="0" />';
$random_banner[4] = '<img src="path/to/banner4.gif" alt="" border="0" />';
$random_banner[5] = '<img src="path/to/banner5.gif" alt="" border="0" />';

$new_banners = $random_banner[$random_number];

vB_Template::preRegister('navbar',array('new_banners' => $new_banners));To make it work, I just dropped this code {vb:raw new_banners} on the template and now it works just as before under vB3.x.

For some (unknown) reason, {vb:raw random.banner.random_number} wasn't working as you suggested, although the arrays were set correctly.

I appreciate your help and borbole (http://www.vbulletin.org/forum/member.php?u=369511) for helping me through this.

I hope other users find this little experience useful in their sites.

borbole
08 Sep 2010, 22:46
Thank you very much Lynne,

I had to add a little bit more and actually change the plugin code to a simpler version.
Inside the plugin I had to create a third variable $new_banners and only pre-registered that variable within template and ran it through parse_templates hook

To make it work, I just dropped this code {vb:raw new_banners} on the template and now it works just as before under vB3.x.

For some (unknown) reason, {vb:raw random.banner.random_number} wasn't working as you suggested, although the arrays were set correctly.

I appreciate your help and borbole (http://www.vbulletin.org/forum/member.php?u=369511) for helping me through this.

I hope other users find this little experience useful in their sites.

Glad to see that you got it solved :)

owning_y0u
01 Oct 2010, 22:14
Just a small question,

i want to create a template that is showing above the header template..
do i need to register this template ? and how do i call this template above the header? its for a suite version of vB4.X

Vikingant
09 Oct 2010, 00:09
I asked this question over at the other VB forum and was directed to this article. Being completely new to all of this stuff and am still learning my way around, can someone please spell this out to me...

Is there a way to easily move the style chooser from the footer to the navbar? I have copied the following from the footer and pasted it into various places but for some reason I only get the chooser box, but it isnt populated with the styles.

<form action="{vb:raw vboptions.forumhome}.php" method="get" id="footer_select" class="footer_select">


<vb:if condition="$show['quickchooser']">
<select name="styleid" onchange="switch_id(this, 'style')">
<optgroup label="{vb:rawphrase quick_style_chooser}">
{vb:raw quickchooserbits}
</optgroup>
</select>
</vb:if>

<vb:if condition="$show['languagechooser']">
<select name="langid" onchange="switch_id(this, 'lang')">
<optgroup label="{vb:rawphrase quick_language_chooser}">
{vb:raw languagechooserbits}
</optgroup>
</select>
</vb:if>
</form>

cellarius
09 Oct 2010, 07:47
You need to find out in the php files where the quickchooserbits and languagechooserbits variables are filled; they also will be registered for the footer template there. Then you need to find a hook that's executed afterwards and register those two variables for the template you want to put it in.

Vikingant
09 Oct 2010, 23:23
You need to find out in the php files where the quickchooserbits and languagechooserbits variables are filled; they also will be registered for the footer template there. Then you need to find a hook that's executed afterwards and register those two variables for the template you want to put it in.

Thank you cellarius
Does this come in english? O.o
Sorry, but I am VERY new to all of this due to necessity and am not familiar with some of the terminology yet.
Where do I look for the PHP files? How do I register variables? How do I find/register a hook?

cellarius
10 Oct 2010, 17:37
The php files (among other stuff) is what you upload to your webspace. How to register variables for templates is what this tutorial is all about, but if you don't have at least basic knowledge of php this may be difficult to do.

Some basics about the vB addon/plugin system can be found here:
http://www.vbulletin.com/docs/html/

Vikingant
14 Oct 2010, 13:59
Thanks for that. I may be getting over excited with wanting to do stuff now that I can. I will definately read up some more. I have found (bluffed) my way through a lot relatively unscathed so far.

Quick hint: Do I look int the FTP or ACP?

Ta

cellarius
14 Oct 2010, 15:23
PHP files you find via FTP, plugins and addons you handle via AdminCP.

Duncan
25 Oct 2010, 07:56
I am using a custom page and it works properly. However, I have listed on the custom page in the style editor {vb:raw navbar2}. I want the template to display what is in my navbar2 style.

This is in the php file for the custom page:

$templater = vB_Template::create('ncsu');
$templater->register_page_templates();
$templater->register('navbar', $navbar);
$templater->register('navbar2', $navbar2);
$templater->register('pagetitle', $pagetitle);
print_output($templater->render());

And it is still not recognizing {vb:raw navbar2}. Should I add something about this? If so, what? Thank you!

kurv
04 Nov 2010, 07:08
Okay guys, I have read the entire thread and my apologies for my coding ignorance. What I am trying to do is, use a different navbar template on the forumdisplay pages than on the home page.

So I added a new template, called navbarforumdisplay

Copied the code from the navbar template into navbarforumdisplay and removed the items I added in the forumhome version that I don't want appearing in the forumdisplay (only items I added to begin with, not vB code :) ).

Then after reading this thread, I created a plugin here

Title: Forumdisplay Navbar
Hook Location: forumdisplay_complete
Exc Order: 5

with the following code
global $template_hook;
$newTemplate = vB_Template::create('navbarforumdisplay');
$template_hook['fd_navbar'] .= $newTemplate->render()

Then I added the following code to the FORUMDISPLAY template

{vb:raw fd_navbar}

and removed
{vb:raw navbar}

Can someone tell me what I am doing wrong, or what is the best way to do this?

Thank you!!!

ROTPAR
06 Nov 2010, 13:34
could anybody please give me a step by step tutorial, how to make this code work in postbit_legacy?

<vb:if condition="$show['fb_likebutton']">
{vb:raw fblikebutton}
</vb:if>

cellarius
07 Nov 2010, 22:50
...
Waaaay too complicated. Go to the normal navbar template and put everything you do not want to appear on forumdisplay inside this condition:
<vb:if condition="THIS_SCRIPT != 'forumdisplay'">code not to be shown on forumdisplay</vb:if>

StarBuG
13 Nov 2010, 09:39
Hello. I need your help.

I need the $pagenumber variable to be available in postbit_legacy so that I can create an url when the thread has multiple pages.

Currently I am using: <a href="http://www.patientenfragen.net/{vb:link thread, {vb:raw thread}}" target="_blank">

but I need it to work this way:

<a href="http://www.patientenfragen.net/{vb:link thread, {vb:raw thread}<vb:if condition="$pagenumber">&amp;page={vb:raw pagenumber}</vb:if>}" target="_blank">

I need the url including the page the user is on.

I am no programmer so even though your explanation is quite detailed I don't really get what I have to do.
I need to register that variable to the postbit_legacy template, but how do I do that?

Sorry for asking such a stupid question but I am totally lost here.

Any help is much appreciated.

StarBuG

Hippy
22 Nov 2010, 23:55
thanks for the time and effort spent on this article

very helpfull

KaiStone
01 Jan 2011, 20:09
Please help me with this issue.

I have a plug in (Location: parse_templates)

if($vbulletin->options['enable_vbadv'] AND in_array($vbulletin->userinfo['usergroupid'], explode(',', $vbulletin->options['vbadv_ug'])))
{
switch($vbulletin->options['vbadv_place'])
{
case 1:
$place = '$navbar';
$fechttemplate = 'FORUMHOME';
break;
case 2:
$place = '$ad_location[ad_navbar_below]';
$fechttemplate = 'navbar';
break;
default:
$place = '$navbar';
$fechttemplate = 'FORUMHOME';
break;
}
$vbulletin->templatecache[$fechttemplate] = str_replace($place, $place . '\n' . fetch_template('forumhome_+++++++_com_adv'), $vbulletin->templatecache[$fechttemplate]);
}



I've tried to fix it like this

if($vbulletin->options['enable_vbadv'] AND in_array($vbulletin->userinfo['usergroupid'], explode(',', $vbulletin->options['vbadv_ug'])))
{
$templater = vB_Template::create('forumhome_+++++++_com_adv');
$templater->register('advheader', $advheader);
$advheader = $templater->render();
switch($vbulletin->options['vbadv_place'])
{
case 1: $template_hook['forumhome_above_forums'] .= $advheader; break;
case 2: $ad_location['global_below_navbar'] .= $advheader; break;
}
}

But it takes effect only when I choose case 1, display below forums. When I choose "Below Navbar", there's nothing displayed. Please help me to fix it.

Thank you very much, and sorry for my bad English.

--------------- Added 1293914180 at 1293914180 ---------------

It's Fixed. Just simple change Location to "global_start"

TheInsaneManiac
03 Jan 2011, 17:48
All I want to do is covert the current fetch template into current VB code. How do I do this in 4.0?
eval('$soundnotification = "' . fetch_template('sound_notification') . '";');

I tried:
$soundnotification .= vB_Template::create('sound_notification')->render();

But to no avail does it work

rob01
05 Jan 2011, 19:52
is posible to do

{vb:raw my_var.userid}

or how i should call for the user id or username?

for example vb3:

<br>User Registration IP Address: $spammerinfo[ipaddress]
<br>User IP Address for Selected Post: $postinfo[ipaddress]

but how to make it work for vb4?
:S

KaiStone
06 Jan 2011, 13:20
is posible to do

{vb:raw my_var.userid}

or how i should call for the user id or username?

for example vb3:

<br>User Registration IP Address: $spammerinfo[ipaddress]
<br>User IP Address for Selected Post: $postinfo[ipaddress]

but how to make it work for vb4?
:S

As my knowledge, if in vB3, the command is $spammerinfo[ipaddress] and $postinfo[ipaddress], so in vB4, the command is

{vb:raw spammerinfo.ipaddress}
{vb:raw postinfo.ipaddress}

rob01
07 Jan 2011, 02:18
uhmm yeah, but the problem is that spammerinfo attribute is not working :S

Lynne
07 Jan 2011, 03:27
uhmm yeah, but the problem is that spammerinfo attribute is not working :S
Did you register the variable for use in that template?

TheInsaneManiac
08 Jan 2011, 02:18
All I want to do is covert the current fetch template into current VB code. How do I do this in 4.0?
eval('$soundnotification = "' . fetch_template('sound_notification') . '";');

I tried:
$soundnotification .= vB_Template::create('sound_notification')->render();

But to no avail does it work

Help

Yaung Sein
09 Jan 2011, 04:20
I want to register $forum in facebook_publishcheckbox template. But I don't know where I set those set those register value in what file.

vB_Template::preRegister('facebook_publishcheckbox',array('forum' => $forum));


facebook_publishcheckbox Template<label id="fb_pulishlabel" for="fb_dopublish">
<img src="{vb:stylevar imgdir_misc}/facebook.gif" alt="{vb:rawphrase publish_to_facebook}" />
{vb:rawphrase publish_to_facebook}
<input type="checkbox" tabindex="1" id="fb_dopublish" value="1" <vb:if condition="in_array($forum['forumid'], array(70,80,81,82,83,88,92,93))"><vb:else />checked="checked" </vb:if>name="fb_dopublish" />
</label>

Please help me, I am a very beginner.

KaiStone
13 Jan 2011, 13:05
Put the register code in a plugin, and call it where your template displays (by choosing hook location). In the case you don't really know what to do, Creat a new plugin and choose hook location is global_start or parse_template

TheInsaneManiac
06 Feb 2011, 06:16
Hello, I hope someone can point in the right direction. I'm trying to port a mod to vb4 which has a number of templates. The php file contains a whole bunch of eval('$template .= "' . fetch_template('templatename') . '";'); lines. The mod uses a main template which then calls the other templates from within the main template using $template references to the other templates.

I've tried a number of different iterations form the first post but I can't get anything but the main template to render. How does one go about making something like this work?


thanks.

Im wondering the same thing.

wonderfulwat
05 Mar 2011, 09:07
I've created a custom template "memberaction_dropdown_one" which I want to have show up in another custom template "postbit1".

Please help show me how to declare this. If anyone has skype it would be very much appreciated if you could walk me through the process in realtime (probably 5 min max). Send me a PM.

brandondrury
07 Mar 2011, 22:03
Just out of curiosity, is there any reason why this wouldn't work in vB 4.1.1? I'm getting some unexpected errors and wanted to rule out that element before I dig TOO deep.

Brandon

cellarius
11 Mar 2011, 17:50
Just out of curiosity, is there any reason why this wouldn't work in vB 4.1.1?
No, none that I'm aware of. This is pretty basic vB4 architecture, and nothing did change there.

Phaedrus
18 Mar 2011, 09:51
This is where one of those "thank you" mods would come in handy. This was a lifesaver, I was able to upgrade a mod that I needed for any upgrade.

ninadbe
23 Mar 2011, 18:47
Is there any way to make plugin that uses remote database connection or use to extract data from other server?
We have vbulletin forum for our site, but our site is located on one server and forum located on another server in order to avoid load.
I want to extract data from main site (which is located on another server) and display it on forum.

I tried lot , searched everywhere. But I not found any specific plugin / mod.

I created custom plugin on my own but it giving errors like
"MySql client ran out of memory"
"Invalid key error"

cellarius
23 Mar 2011, 19:44
This is question has nothing to do with the article this discussion thread is for. Please open your own thread in an appropriate forum.

TalkVirginia
01 Apr 2011, 08:29
I'm trying to capture a rendered/parsed template to a variable like so:



$templater = vB_Template::create('test');
$templater->register('userid', $userid);
$templater->register('bbtitle', $bbtitle);
$templater->register('homeurl', $homeurl);
$templater->register('forumurl', $forumurl);
$myvar = $templater->render();

echo $myvar;



I would expect that myvar would contain the parsed template, but it comes up empty.

Can anyone help me?

gibigbig
02 Apr 2011, 07:48
using in a mod:

1) make a new plugin
Hook: global_start
code:
$template_hook['footer_javascript'] .= '<b>HTML goes here</b>';

spent a good few hours looking for how to do such a simple task this article has way over complicated.
also, tested and working in vb 4.1.2


also note that you can even make your own hook by using the code:
{vb:raw template_hook.hook_name}
in any template
simple stuff.

cellarius
02 Apr 2011, 08:05
using in a mod:

1) make a new plugin
Hook: global_start
code:
$template_hook['footer_javascript'] .= '<b>HTML goes here</b>'; spent a good few hours looking for how to do such a simple task this article has way over complicated.
also, tested and working in vb 4.1.2
Sorry that my article turned out to be too complicated for you. If you don't want to render a template, it may have not been made for you. Anyway - leave the template rendering aside, and you have exactly your line of code at the end of the code that covers template hooks.

By the way: hook global_start is not a good choice. It does not exist in the CMS and will vanish from any part of the product that gets rewritten to the OOP framework in future.

Boofo
02 Apr 2011, 08:12
I'm trying to capture a rendered/parsed template to a variable like so:



$templater = vB_Template::create('test');
$templater->register('userid', $userid);
$templater->register('bbtitle', $bbtitle);
$templater->register('homeurl', $homeurl);
$templater->register('forumurl', $forumurl);
$myvar = $templater->render();

echo $myvar;



I would expect that myvar would contain the parsed template, but it comes up empty.

Can anyone help me?

This:

$myvar = $templater->render();


should be this:

$myvar .= $templater->render();

rlarner
05 Apr 2011, 21:49
I'm struggling with getting data from a variable into one of the stock templates. Here's what I've done:
Created a custom plugin with the hook location set to "global_start":
$roscohtml = "<div>HELLO WORLD!</div>";
error_log($roscohtml);
vB_Template::preRegister('header',array('roscohtml'=>$roscohtml));

Then I customized the header template to contain this:
<div class="above_body"> <!-- closing tag is in template navbar -->
<div>test before</div>
{vb:raw roscohtml}
<div>test after</div>

Unfortunately the variable isn't being output. I do see the contents in the error log, so I know it's firing.

Any tips?

Thanks,
Rosco

--------------- Added 1302039172 at 1302039172 ---------------

OK, I think I found the problem - the global_start hook is not the right place for this to live. I moved my code to the parse_templates hook and the data is now available.

Is there a document which outlines the best way to leverage the hooks, or at least where each is called in the flow?

Rosco

bela-meaad
25 Apr 2011, 20:42
as templates no longer get output using eval
i tried to change it but seems not working.

can anyone help me with this code?


if ($vbulletin->options['card_onoff'] AND THIS_SCRIPT != 'private' AND THIS_SCRIPT != 'login')
{
if( $vbulletin->userinfo['usergroupid']!=8 OR $vbulletin->userinfo['usergroupid']!=3 OR $vbulletin->userinfo['usergroupid']!=1 )
{
$istherewinner=mysql_query("SELECT `value` FROM `setting` WHERE `varname` = 'card_carintwin' LIMIT 1");
while ($yeswinner = $db->fetch_array($istherewinner))
{
$bigwinner =$yeswinner[value];
}

if($bigwinner)
{
eval('$card_win_index = "' . fetch_template('card_win_index') . '";');
$ad_location['global_below_navbar'] .= $card_win_index;
}
else
{
eval('$card_index = "' . fetch_template('index_card') . '";');
$ad_location['global_below_navbar'] .= $card_index;
}
}
}

Boofo
07 May 2011, 16:48
http://www.vbulletin.org/forum/showpost.php?p=2180014&postcount=151

BirdOPrey5
05 Jul 2011, 21:09
I hoping this isn't too far off topic bt if possible I think it would make a good addition to the article...

What if I want to override an existing template with a new template. Basically ignore whatever is in a given template and render a new template, and copy the new template to the old template? Is that possible?

I've tried stuff like:


$templater = vB_Template::create('my_new_template');
$templater->register('myvar', $myvar);
$globaltemplates['existing_vb_template'] = $templater->render();


in all the various template hooks to no avail. I've also tried using $vbulletin->templatecache['existing_vb_template'] in the last line instead of $globaltemplates and also did not work.

Is what I'm asking possible? Seems like it should be... Any input would be appreciated.

Boofo
05 Jul 2011, 21:58
Yes, it can be done easily, if what you are wanting is what I understand it to be. As an example, here is what I did for that:

$templater = vB_Template::create('boofo_forumhome_event');
$templater->register('callink', $callink);
$templater->register('daysevents', $daysevents);
$templater->register('eventdate', $eventdate);
$templater->register('eventdates', $eventdates);
$upcomingevents .= $templater->render();

$vbulletin->templatecache['forumhome_event'] = $vbulletin->templatecache['boofo_forumhome_event'];

BirdOPrey5
05 Jul 2011, 23:40
Great, Thanks Boofo!

It might be worth mentioning for anyone else- you have to register any variables used to the ORIGINAL template (the one you are overriding) not the new template... At least that's the only way it's working for me. (On parse_templates hook)

Boofo
06 Jul 2011, 00:12
Are you sure? I used the same variables when I did it but I would think you only need to pre-register the variables you are going to use, not the other way around.

I did the above code in forumhome_start. Did you try the process_templates_complete hook?

BirdOPrey5
06 Jul 2011, 02:34
Maybe I didn't explain it right... in your example registering callink and the others to boofo_forumhome_event didn't do anything for me- I had to preRegister them to forumhome_event for them to work. I tried both parse_templates and process_templates_complete hooks.

To me it makes sense since the forum thinks it's outputting forumhome_event, and this is confirmed by viewing template names in the HTML source code.

Boofo
06 Jul 2011, 02:53
Well, yes and no. Since I did it in the forumhome_start hook, it needed those pre-registered for my new template. As long as the variables are good at that hook, then it will work the way I did it.

The forumhome doesn't care about the old template as long as I pre-register everything for my new template. Doing it in the parse_templates hook might be why it didn't work for you with your code. You would have to check whether whatever variables you are pre-registering have already been validated at whatever hook you are using.

Now I'm getting confused. And it hurts! LOL

BirdOPrey5
06 Jul 2011, 03:45
Well, yes and no. Since I did it in the forumhome_start hook, it needed those pre-registered for my new template. As long as the variables are good at that hook, then it will work the way I did it.

The forumhome doesn't care about the old template as long as I pre-register everything for my new template. Doing it in the parse_templates hook might be why it didn't work for you with your code. You would have to check whether whatever variables you are pre-registering have already been validated at whatever hook you are using.

Now I'm getting confused. And it hurts! LOL

Don't be confused- the important thing is it works and all is well. :up:

EquinoxWorld
08 Jul 2011, 18:38
Hello everyone, I have been reading this article over and over again trying to figure out what I am doing wrong. Basically I am trying to put the contents of one template into another using a plug in. The template in question are:

-OFTW
-COFTW_FAQ

I want to be able to put the contents of template COFTW_FAQ into a variable that I can then use in OFTW template. I am using a script (oftw.php) which uses the OFTW template; I need to be able to insert the contents of COFTW_FAQ into that template using a plug-in. So this is what I have so far:

Plug-in 1: Hook: Global Start

$templater = vB_Template::create('COFTW_FAQ');
$templater->register('oftw_faq', $oftw_faq);
$mytemplate_rendered = $templater->render();

Plug-in 2: Hook: Global Start

$templater = vB_Template::create('OFTW');
$templater->register('COFTW_FAQ', $mytemplate_rendered);
$mytemplate2_rendered = $templater->render();

And I am using the following variable to call the contents of COFTW_FAQ into OFTW template:

{vb:raw COFTW_FAQ}

With no avail; I get a blank where the content of the variable should be. Any ideas what I am doing wrong anyone??

Please Help I have been hitting myself in the head for the last 4 hours! :(

--------------- Added 1310166367 at 1310166367 ---------------

UPDATE!!!

After more thinking... I can see that I was a bit off, I am now using only plug in to try and accomplish what I want but still just blank...

Hook Location: Process Templates Complete
$templater = vB_Template::create('OFTW_FAQ');
$oftw_faq = $templater->render();
vB_Template::preRegister('OFTW',array('oftw_faq ' => $oftw_faq));

Using: {vb:raw oftw_faq} in the OFTW template but still nothing... Am I getting closer??? :(

--------------- Added 1310224935 at 1310224935 ---------------

GOT IT!!! FINALLLLY!!!!! xD

I had to just register my variable in the actual oftw.php file . Since it was a custom page the script did not have the variable registered so I added $templater->register('oftw_faq', $oftw_faq); to the oftw.php file and added the last plug-in above and voila! Perfect!! This opens up a whole new world for me. :) Anywho, just thought i'd share my conquering :)

cellarius
11 Jul 2011, 07:34
Congrats - good to see you got it working :D

BirdOPrey5
11 Jul 2011, 14:19
Hello everyone, I have been reading this article over and over again trying to figure out what I am doing wrong. Basically I am trying to put the contents of one template into another using a plug in. The template in question are:

-OFTW
-COFTW_FAQ

I want to be able to put the contents of template COFTW_FAQ into a variable that I can then use in OFTW template. I am using a script (oftw.php) which uses the OFTW template; I need to be able to insert the contents of COFTW_FAQ into that template using a plug-in. So this is what I have so far:

Plug-in 1: Hook: Global Start
...

As has been mentioned here before global_start is a bad hook to use in VB4. It was included for compatibility with older mods and is expected to be removed at some point- you can't count on it existing in non-forum parts of the site.

global_bootstrap_init_start should be used instead of global_start in most circumstances.

EquinoxWorld
11 Jul 2011, 21:17
As has been mentioned here before global_start is a bad hook to use in VB4. It was included for compatibility with older mods and is expected to be removed at some point- you can't count on it existing in non-forum parts of the site.

global_bootstrap_init_start should be used instead of global_start in most circumstances.

For rendering template and such which is the most recommended then? I'm assuming "process_template_complete" ? Or does it depend on each case?

Adrian Schneider
11 Jul 2011, 21:23
If you are going to assign several variables in a row, you may want to use the quickRegister function, as it is a lot more readable and clear what is happening (IMO).

$page = vB_Template::create('xxx_newpost');
$page->quickRegister(array(
'newpost' => $newpost,
'messagearea' => $messagearea,
'editorid' => $editorid,
'prefix_options' => fetch_prefix_html($foruminfo['forumid'], $newpost['prefixid'], true),
'tagcloud' => prepare_tagcloudlinks(prepare_tagcloud('usage')),
'faqs' => xxx_fetch_faqs('vb3_board_usage'),
'topics' => xxx_fetch_topics(),
'strategies' => xxx_fetch_strategies($parentId),
'moderators' => xxx_fetch_moderators(),
));

BirdOPrey5
11 Jul 2011, 22:32
For rendering template and such which is the most recommended then? I'm assuming "process_template_complete" ? Or does it depend on each case?

it depends where the template will be needed, if it will only be on showthread than one of the showthread hooks... but if it might be called anywhere than process_templates_complete or parse_templates seem to work. I don't know if one is better than the other.

cellarius
12 Jul 2011, 06:01
As a general rule: Use a hook that is only called where you need the variable. Normally, you execute code before registering to get the values, and you want to run that only if it's needed. Of course, using stuff like if THIS_SCRIPT will do the job, too.

Murtific
20 Jul 2011, 03:44
i learned how to make custom templates like this. I have a variable that i want to be able to use on the header on every page in vbulletin. I cant get it to save my variable globaly tho. I'm only able to use this var within the template. I read the part where it talked about Save into an array and preregister to use in an existing/stock template. but could not get it to work. by the way, I have no idea how to show code on here


$eventlist = mysql_query("SELECT * FROM thread WHERE forumid = 8 ORDER BY dateline DESC", $connection);
if (!$eventlist) {
die("Database selection failedquery:SEEPASSWORD: " . mysql_error());
}
while ($row = mysql_fetch_array($eventlist)) {
$zthreadid .= $row["threadid"];
$zdateline .= $row["dateline"]."<br />";
$zlink .= "<a href='showthread.php?{$row["threadid"]}'>" . $row["title"]."</a>" . "<br />";
}

$templater = vB_Template::create('threads');
$templater->register('zthreadid', $zthreadid);
$templater->register('zlink', $zlink);
$templater->register('zdateline', $zdateline);
$zlink2['$zlink'] = $templater->render();
vB_Template::preRegister('header',array('zlink2' => $zlink2));



In the stock header template I put {vb:raw zlink2} but its not showing up. Although in the template I created it displays fine due to the fact that I copied the entire header template and stuck it in my template instead of calling {vb:raw header} in my custom template. Any ideas???

HMBeaty
20 Jul 2011, 03:49
by the way, I have no idea how to show code on here
Just paste your code you're using inside code/html/php tags. For example:

your code here[./code]
Would be
[CODE]your code here
your code here[./php]
Would be
[PHP]your code here
your code here[./html]
Would be
[HTML]your code here
Obviously without the "." in the tags though :)

Murtific
20 Jul 2011, 04:53
Just paste your code you're using inside code/html/php tags. For example:

your code here[./code]
Would be
[CODE]your code here
your code here[./php]
Would be
[PHP]your code here
your code here[./html]
Would be
[HTML]your code here
Obviously without the "." in the tags though :)

Thanks, got it. Now back to my previous post, anybody have any ideas?

BirdOPrey5
20 Jul 2011, 13:34
What hook is your code on?

Murtific
20 Jul 2011, 16:32
what's a hook? I dont have a hook. I ended up just doing this. I basically just added my database code to the forum.php file and got it to work, but i have to modify every template like I mentioned in this thread, i'd rather use this thread http://www.vbulletin.org/forum/showthread.php?t=267120

kh99
20 Jul 2011, 17:20
what's a hook? I dont have a hook. I ended up just doing this. I basically just added my database code to the forum.php file and got it to work,

That's probably the issue - if you put it in after global.php, it's too late to affect the header. (Edit: actually that's wrong, I think you have until another template is rendered, so what you did could have worked, but try it with a plugin anyway.)

See my post in the other thread.

Dave-ahfb
23 Jul 2011, 18:36
First let me say that I am not PHP literate, but can find my way around 9 times out of 10.

I am creating custom templates to include my non vb scripts but am having troubles when trying to include a variable(?) from this script in any template outside the main body.

I will try to be as detailed as possible, hopefully any responses will include the information I give as a real life example so that I can get an understanding of what was done.


Goal: to take $companyname from the below script and add it to my page title, navbits etc. (currently I only get echos of $companyname or {vb:raw companyname}, depending on where I am in my efforts.
if (isset($_GET['company']))
$company = $_GET['company'];
else
$company = '100megs';
$result = mysql_query("select * from hostwebhost where companyname = '$company'");
if (!$result) {
$numrows = 0;
} else {
$numrows = mysql_num_rows($result);
}
for($x=0;$x<$numrows;$x++){
while ($row = mysql_fetch_array($result)){
$host_id = $row[0];
$companyname = $row[1];
$emailaddress = $row[2];
$URL = $row[3];
$track = $row[4];
$imgtop = $row[5];
$imgright = $row[6];
$imgbody = $row[7];
$joined = $row[8];
$password = $row[9];
$isvalid = $row[10];
$supportlist = $row[11];
$street1 = $row[12];
$street2 = $row[13];
$city = $row[14];
$state = $row[15];
$zip = $row[16];
$country = $row[17];
$contactname = $row[18];
$contactphone = $row[19];
$contactfax = $row[20];
$suggested = $row[21];
$comdescrip = $row[22];
$registered = $row[23];

plugin info:
location: global_bootstrap_init_start
title: Webhost-php Include
execution order: 5
code:
ob_start();
ob_start();
include('/srv/www/findnewhosting.com/public_html/webhost1.php');
$webhost = ob_get_contents();
ob_end_clean();
vB_Template::preRegister('webhost-php', array('webhost' => $webhost));


As you can see the script is webhost1.phpwhich includes the first set of code above. Please note that the custom page is webhost.php which contains the following:
<?php

// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################

define('THIS_SCRIPT', 'webhosting');
define('CSRF_PROTECTION', true);
// change this depending on your filename

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array();

// get special data templates from the datastore
$specialtemplates = array();

// pre-cache templates used by all actions
$globaltemplates = array('webhost-php',);

// pre-cache templates used by specific actions
$actiontemplates = array();

// ######################### REQUIRE BACK-END ############################
chdir ('/srv/www/findnewhosting.com/public_html');

require_once('/srv/www/findnewhosting.com/public_html/global.php');

// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################

$navbits = construct_navbits(array('' => '&nbsp;</span></li><li class="navbit"><span><a href="/">Home</a></span></li><li class="navbit"><span><a href="../hostindex.php">Web Hosting</a></span></li><li class="navbit lastnavbit"><span>{vb:raw companyname}

'));
$navbar = render_navbar_template($navbits);

// ###### YOUR CUSTOM CODE GOES HERE #####
$pagetitle = '$companyname';
$templater = vB_Template::create('headerincludea');
$headerincludea = $templater->render();
$templater = vB_Template::create('webhost-php');
$templater->register_page_templates();
$templater->register('navbar', $navbar);
$templater->register('pagetitle', $pagetitle);
$templater->register('sidebarext', $sidebarext);
$templater->register('sidebaropen', $sidebaropen);
$templater->register('headerincludea', $headerincludea);


print_output($templater->render());
?>


webhost-php(template):
{vb:stylevar htmldoctype}
<html xmlns="http://www.w3.org/1999/xhtml" dir="{vb:stylevar textdirection}" lang="{vb:stylevar languagecode}" id="vbulletin_html">
<head>
<title>{vb:raw companyname}</title>
{vb:raw headerincludea}
{vb:raw headinclude_bottom}
</head>
<body>
{vb:raw header}
{vb:raw navbar}
{vb:raw sidebaropen}
<br />
<div id="pagetitle">
<h1>&nbsp;&nbsp;{vb:raw pagetitle}</h1><br />
</div>
<div class="blockbody">
<div class="blockrow">
<div align="center">

{vb:raw webhost}

</div>
</div>
</div>
{vb:raw sidebarext}


{vb:raw footer}
</body>
</html>

If there is any other info I can give to make it easier to solve just let me know.

Dave

BirdOPrey5
23 Jul 2011, 19:30
I don't know if it's your only problem but you didn't register $companynanme in your webhost1.php file, so it won't show in your template.

Dave-ahfb
23 Jul 2011, 19:48
Could you dumb that down please?

BirdOPrey5
24 Jul 2011, 14:50
Could you dumb that down please?

At the end of webhost1.php you have this code:

$templater = vB_Template::create('webhost-php');
$templater->register_page_templates();
$templater->register('navbar', $navbar);
$templater->register('pagetitle', $pagetitle);
$templater->register('sidebarext', $sidebarext);
$templater->register('sidebaropen', $sidebaropen);
$templater->register('headerincludea', $headerincludea);


print_output($templater->render());

You need to add this line:


$templater = vB_Template::create('webhost-php');
$templater->register_page_templates();
$templater->register('navbar', $navbar);
$templater->register('pagetitle', $pagetitle);
$templater->register('sidebarext', $sidebarext);
$templater->register('sidebaropen', $sidebaropen);
$templater->register('headerincludea', $headerincludea);
$templater->register('companynanme', $companynanme);

print_output($templater->render());


ALL variables you need to use in a template MUST be registered to a template before you use it. If you use any other variables you must register them also.

Dave-ahfb
24 Jul 2011, 16:26
Thank you so much. As soon as I can put this paint brush down I will give it a shot.

Dave

heugabel
26 Jul 2011, 19:19
$search_text = '<!-- end logged-in users -->';
$vbulletin->templatecache['FORUMHOME'] = str_replace($search_text, $search_text . fetch_template('forumhome_xyz'), $vbulletin->templatecache['FORUMHOME']);

how i can rewrite this for vb4?

thank you

cellarius
26 Jul 2011, 19:30
This has been described around the forum several times; either search or open your own thread, this is not related to the topic of this tutorial.

EquinoxWorld
04 Aug 2011, 05:50
Hello everyone, is there any way to include for example this php:

cotw_func_contest_num.php?do=sotw

As a variable in a plugin, then use it in a template?

I also created this (http://www.vbulletin.org/forum/showthread.php?t=267926)thread but am also posting here to see if anyone had any further ideas we could try. Any info would be very much appreciated. Thanks for your time everyone.

MikeF
04 Aug 2011, 06:14
I've been driven nuts. All I want to do is output $random_number using rand(1,99999) and I'm stuck.. why have they made this insanely difficult?

kh99
05 Aug 2011, 22:12
I've been driven nuts. All I want to do is output $random_number using rand(1,99999) and I'm stuck.. why have they made this insanely difficult?

It actually does make sense, although I'll admit it's not obvious why. What have you tried? You should be able to do something like in a plugin:

$random_number = rand(1,99999);
vB_Template::preRegister('template_name',array('random_number' => $random_number));

hook location parse_templates is probably a good choice. Of course you need to change template_name to the actual name of the template you want to use the random number in.

Then in the template put
{vb:raw random_number}

RobDog888
15 Aug 2011, 01:40
Ok been banging my head on this for quite some time now and completely ready to throw in the towel. I dont know why vB had to make things so damn difficult! It used to be really easy and straight forward to extend vB but not so much now.

I just want to pull in my custom template for adding a value to the postbit userifo part using the template hook "postbit_userinfo_right_after_posts"

The variable $post[field5] is already pulled in as I can do the eval like so to test it in the plugin...

if ($post['field5'])
{
$templater = vB_Template::Create('postbit_name');
$template_hook['postbit_userinfo_right_after_posts'] .= $templater->render();
}

My templates phrases are eval'd and outputted in the hook location but $post[field5'] is blank yet how did it evaluate as true if its empty?
If I hard code the template instead of creating it it works fine but I want it to be properly developed and not hacked.

Thanks

cellarius
15 Aug 2011, 08:59
Because it's filled in your PHP script, but you never registered it for use in your template, and that's why it's empty there.

The tutorial does state (in bold red ;)) that you have to register every variable and array you want to use in your custom template. Try:

if ($post['field5'])
{
$templater = vB_Template::Create('postbit_name');
$templater->register('post', $post)
$template_hook['postbit_userinfo_right_after_posts'] .= $templater->render();
}

Then you should be able to use {vb:raw post.field5} in your template.

RobDog888
16 Aug 2011, 05:30
Thank You for the reply but I guess I will have to start over at square 1 to get a better understanding of the new vB4 architechure

Ok now I made that change and it work! So even though the variable/array is a standard vB one because I made a custom template I have to register the standard variables too it seems. I thought it was just our custom variables

demo7up
17 Aug 2011, 15:40
FINAL WORKING CODE:

Product: vBulletin
Title: Insert Simple PHP
Execution order: 5
Hook Location: global_start
PHP code:
ob_start();
include('simple.php');
$simple_php = ob_get_contents();
ob_end_clean();

vB_Template::preRegister('navbar',array('simple_php' => $simple_php));
Plugin is active: Yes

Now, go to the NAVBAR template and insert
{vb:raw insert_simple_php}
just under the code
{vb:raw ad_location.global_below_navbar}

Im trying to use this code to include a php file in my custom page this is what im using

ob_start();
include('../www/gearstore/jdmgear.php');
$templatevalues['insert_simple_php'] = ob_get_contents();
ob_end_clean();
vB_Template::preRegister('JDMGEAR', $templatevalues);

In my template i have


{vb:raw insert_simple_php}


It seems it wants to work but im just getting a gray box as such.

actual page http://nycjdm.com/jdmgear.php any ideas?

--------------- Added 1313595423 at 1313595423 ---------------

Im trying to use this code to include a php file in my custom page this is what im using

ob_start();
include('../www/gearstore/index.php');
$templatevalues['insert_simple_php'] = ob_get_contents();
ob_end_clean();
vB_Template::preRegister('JDMGEAR', $templatevalues);

In my template i have


{vb:raw insert_simple_php}


It seems it wants to work but im just getting a gray box as such.

actual page http://nycjdm.com/jdmgear.php any ideas?

i figured it out, it was the action script in the swf.. i changed some paths and it is now working ..

I have everything working now i just need to figure out how to intergrate it's login with vb4 if anyone could point me in the right direction that would be great.

HMBeaty
19 Aug 2011, 01:38
Ok, I'm probably overlooking something, or didn't do something right, or something lol, but this is my first time trying to include a custom template within another custom template on vB 4 (it was SO much easier on vB 3 :()

Anyway, this is where I'm at so far:
Plugin
Hook location: process_templates_complete
$templater = vB_Template::create('usml_military_ranks_sidebar');
$usml_military_ranks_sidebar = $templater->render();
vB_Template::preRegister('usml_military_ranks',array('usml_military_ranks_sideba r' => $usml_military_ranks_sidebar));

Template
I'm calling my sidebar template in my template usml_military_ranks (and many others) by using:
{vb:raw usml_military_ranks_sidebar}

PHP file
In the PHP file for usml_military_ranks I have:
$templater = vB_Template::create('usml_military_ranks');
$templater->register_page_templates();
$templater->register('navbar', $navbar);
$templater->register('usml_military_ranks_sidebar', $usml_military_ranks_sidebar);
$templater->register('mainpagetitle', $mainpagetitle);
$templater->register('imp_vars', $imp_vars);
$templater->register('pages', $pages);
print_output($templater->render());
So what am I missing? lol :confused:

kh99
19 Aug 2011, 02:07
You might try taking this line out of the php file:

$templater->register('usml_military_ranks_sidebar', $usml_military_ranks_sidebar);


you don't need this and the PreRegister, and this line might actually be registering an undefined variable.

HMBeaty
19 Aug 2011, 02:12
You might try taking this line out of the php file:

$templater->register('usml_military_ranks_sidebar', $usml_military_ranks_sidebar);
you don't need this and the PreRegister, and this line might actually be registering a null value.
LOL! That did it! It's always something simple I end up overlooking :o Thanks!

Raeven
28 Aug 2011, 21:05
Hi, I kinda only have a short question (before I waste another few days of my life, because I didn't wanted to ask for help lol).

My Problem is, that I would like to hook a template on {vb:raw header} (so I don't need any Template edits anymore).
But all I get to work is, when I add in for example Forumhome Template {vb:raw header2} (then my template gets shown, but not if I try to use the real one).

So the Question is:
Is it actual possible or not (to use {vb:raw header})?

The Plugin Code I am using:

$templater = vB_Template::create('dev3_main');
$templater->register('my_var', $my_var);
$templater->register('my_array', $my_array);
$templatevalues['header'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);

hook: process_template_complete (tried also a few others).

And sorry for asking stupid Questions ;).

kh99
30 Aug 2011, 22:22
Is it actual possible or not (to use {vb:raw header})?

Sorry, you were trying to save a few days but it took a few days to get an answer. :o

But the answer is that it probably won't work because I think if 'header' gets registered somewhere else (which it probably is, just before the template is rendered), it will override what you pre-registered.

Raeven
31 Aug 2011, 06:48
That's what I almost feared. So back to thinking how to get rid of the last template edit.

And thanks for the answer.

cellarius
31 Aug 2011, 09:25
It may not be wise to use additional templates etc. just to get rid of a template edit. It adds considerable overhead.

Raeven
06 Sep 2011, 00:41
There is always 2 things to consider:

- the right way
- the way people / customers and such prefer it (and thats usually no template edits :P)

zhai
28 Nov 2011, 09:34
I have been trying to do this for days, but ended up failing all the times. I have read this entire thread twice, from page 1-14 but still couldn't figure this out.

So I'm trying to change this part of showthread:
http://www.vbulletin.org/forum/attachment.php?attachmentid=134753&stc=1&d=1322471332

I want to change it into my own moderation action instead of just closing the thread. I want to change the template with plug-in, but I couldn't get the right variable in which the informations about showthread quickreply are stored. On the early page of this thread, someone tried to change the footer just by accessing $footer .= "things to add"; on process_template_complete. So what variable should I be focusing on with my problem? I have already prepared a new template to replace that "checkbox", I just don't know how to access the existing template by using a plugin.

Any help is appreciated..

HMBeaty
08 Jan 2012, 09:44
Ok, I'm obviously missing something, but not sure what. I'm trying to display a variable in the header template, and what I have works just fine in the navbar. Here's what I have to display my mod in the navbar (this works):
$templater = vB_Template::create('usml_navnet_navbar');
$template_hook[navtab_end] .= $templater->render();

And this is what I was trying for the header (this doesn't work):
$templater = vB_Template::create('usml_navnet_header');
$templatevalues['navnet'] = $templater->render();
vB_Template::preRegister('header', $templatevalues);

And, I believe, according to the 1st post, I would just add {vb.raw navnet} in the header template. However, it's not working, so I'm obviously overlooking something...

BirdOPrey5
08 Jan 2012, 17:45
What hook are you using? Header is rendered early, you may need a hook that is executed earlier.

HMBeaty
08 Jan 2012, 18:57
What hook are you using? Header is rendered early, you may need a hook that is executed earlier.

parse_templates

kh99
08 Jan 2012, 20:21
If you switch the template names (just for a test), does it still only work in the navbar?

HMBeaty
09 Jan 2012, 00:44
Still not working, here is the complete code in use atm...

(code removed :))

kh99
09 Jan 2012, 01:02
... the variable I'm trying to use in the header is {vb.raw navnet}, but it doesn't show anything but the raw variable...

Oh, that's different, I thought you were seeing nothing. But I think it's just that it should be vb:raw instead of vb.raw (I totally missed that in your above post).

HMBeaty
09 Jan 2012, 02:35
Oh, that's different, I thought you were seeing nothing. But I think it's just that it should be vb:raw instead of vb.raw (I totally missed that in your above post).
Lmao, wow! It was definately ":" instead of ".". I can't believe I did that :o. Thanks. On a side note, any idea as to how to adjust the position of a Google+ button? I've been at it for several hours, and it just doesn't seem to move :confused: Figured that out finally :p

TheSupportForum
13 Jan 2012, 04:29
i need help parsing a code into HEADER template using plugin

basically i need to insert a code after

<div id="toplinks" class="toplinks"> i dont want a template, i just want the plugin to insert a code directly after that shown above

using something like



$find <div id="toplinks" class="toplinks">
$mycode <div style="float:right; margin: 5px -12px 5px 10px;">{vb:raw mycode </div>

i am not sure the rest but i know its something like that

Boofo
13 Jan 2012, 04:44
Try this in the parse_templates hook:

require_once(DIR . '/includes/class_template_parser.php');
$parser = new vB_TemplateParser('<div id="toplinks" class="toplinks">');
$parser->dom_doc = new vB_DomDocument($parser->fetch_dom_compatible());
$find = trim($parser->_parse_nodes($parser->dom_doc->childNodes()));

$parser = new vB_TemplateParser('<div style="float:right; margin: 5px -12px 5px 10px;">{vb:raw mycode}</div>');
$parser->dom_doc = new vB_DomDocument($parser->fetch_dom_compatible());
$replace = trim($parser->_parse_nodes($parser->dom_doc->childNodes()));

$vbulletin->templatecache['header'] = str_replace($find, $find . $replace, $vbulletin->templatecache['header']);
unset($find, $replace);

TheSupportForum
13 Jan 2012, 04:55
Try this in the parse_templates hook:

require_once(DIR . '/includes/class_template_parser.php');
$parser = new vB_TemplateParser('<div id="toplinks" class="toplinks">');
$parser->dom_doc = new vB_DomDocument($parser->fetch_dom_compatible());
$find = trim($parser->_parse_nodes($parser->dom_doc->childNodes()));

$parser = new vB_TemplateParser('<div style="float:right; margin: 5px -12px 5px 10px;">{vb:raw mycode}</div>');
$parser->dom_doc = new vB_DomDocument($parser->fetch_dom_compatible());
$replace = trim($parser->_parse_nodes($parser->dom_doc->childNodes()));

$vbulletin->templatecache['header'] = str_replace($find, $find . $replace, $vbulletin->templatecache['header']);
unset($find, $replace);


I thank you very much it worked 100% :)

updating templates this way works perfect without the need to go into the template to manually input it
thx

Boofo
13 Jan 2012, 05:01
I thank you very much it worked 100% :)

updating templates this way works perfect without the need to go into the template to manually input it
thx

You actually had doubts it would work? ;)

TheSupportForum
13 Jan 2012, 05:17
You actually had doubts it would work? ;)

lol, i have lost touch with vb coding in a long time, i just need to get used to it, plus i am glad you repsonded i have seen your great work and advice on here
many thanks

Boofo
13 Jan 2012, 05:42
lol, i have lost touch with vb coding in a long time, i just need to get used to it, plus i am glad you repsonded i have seen your great work and advice on here
many thanks

vb 4 handles str_replace differently, for some reason. Glad I could help. ;)

HMBeaty
13 Jan 2012, 06:55
Try this in the parse_templates hook:

require_once(DIR . '/includes/class_template_parser.php');
$parser = new vB_TemplateParser('<div id="toplinks" class="toplinks">');
$parser->dom_doc = new vB_DomDocument($parser->fetch_dom_compatible());
$find = trim($parser->_parse_nodes($parser->dom_doc->childNodes()));

$parser = new vB_TemplateParser('<div style="float:right; margin: 5px -12px 5px 10px;">{vb:raw mycode}</div>');
$parser->dom_doc = new vB_DomDocument($parser->fetch_dom_compatible());
$replace = trim($parser->_parse_nodes($parser->dom_doc->childNodes()));

$vbulletin->templatecache['header'] = str_replace($find, $find . $replace, $vbulletin->templatecache['header']);
unset($find, $replace);
I can't say I've ever seen this done :eek: I might have to use this in the future :D

Boofo
13 Jan 2012, 07:34
Go for it. An unnamed dev gave it to me a long while back.

clubvr4
23 Feb 2012, 19:18
Hey all,

I think i'm being really dumb here, looking for some help.

In my Navbar Template i want to call another template that i want to create, rather that adding code irectly into the navbar template.

Am i right in thinking that i have to register the code in a php file on the server, or can i do this all via a plug in and templates? if so, does anyone have some code for a simple example, i.e. call 1 new template from within another VB default template? - I ask because unless i am mistaken what i've read thus far seems to focus more on adding code to PHP files.

Currently running 4.1.10.

The template I want to call from navbar template is called memberbar_basic.

kh99
26 Feb 2012, 00:26
The template I want to call from navbar template is called memberbar_basic.

You would create a new plugin with code something like this:

$templater = vB_Template::create('memberbar_basic');
$templater->register('my_var', $my_var); // one or more of these if memberbar_basic uses variables, otherwise leave it out.
$memberbar_basic = $templater->render();
vB_Template::preRegister('navbar', array('memberbar_basic' => $memberbar_basic));


and you would put {vb:raw memberbar_basic} in the navber template. Hook location parse_templates would probably be a good place for your plugin.

clubvr4
27 Feb 2012, 10:20
Hiya,

Thanks for responding - I can't seem to get it to work though, let me review whats currently configured.

Template = memberbar_member_basic
Template content = memberbar member basic test.

Plugin name = memberbar_member_basic
Plugin Hook = Parse Templates
Plugin Content =
$templater = vB_Template::create('memberbar_member_basic');
$memberbar_member_basic = $templater->render();
vB_Template::preRegister('navbar', array('memberbar_member_basic' => $memberbar_member_basic));

Navbar Template (at bottom) i've placed - {vb:raw memberbar_member_basic}

I tried moving {vb:raw memberbar_member_basic} to other templates, specifically forumhome but its still not rendering.

would i have to use variables? if so, is there a guide/overview of what variables would bee needed anywhere?

Thanks
B

BirdOPrey5
27 Feb 2012, 10:24
Off hand there's a typo in the middle line, it's missing the first "m" in "memberbar"

If that error is in your real code it wouldn't work.

clubvr4
27 Feb 2012, 14:04
haha, now i do really feel stupid....

ok, modified my thread correcting the typo and im please to say its working!..

/grabs coat..

(p.s. thank you!)

--------------- Added 1330432890 at 1330432890 ---------------

--------------- Added 1330432974 at 1330432974 ---------------

Progressing from my previous query.

I need to register some variables to allow notifications to be registered in my plugin (Post # 216)

I've tried following this guide here..

https://www.vbulletin.com/forum/showthread.php/360905-How-can-I-change-the-notifications-menu-place

I attempted the following, to no avail.

Plugin name = memberbar_member_basic
Plugin Hook = Parse Templates
Plugin Content =
$templater = vB_Template::create('memberbar_member_basic');
$memberbar_member_basic = $templater->render();vB_Template::preRegister('navbar', array('notifications_menubits' => $notifications_menubits));
vB_Template::preRegister('navbar', array('memberbar_member_basic' => $memberbar_member_basic));
vB_Template::preRegister('navbar', array('notifications_menubits' => $notifications_menubits));

I then moved the notifications code from header to the memberbar_member_basic template, which for reference makes the dropdown appear but does not show notifications nor total notifications.

Code moved.

<vb:if condition="$notifications_total">
<li class="popupmenu notifications" id="notifications">
<a class="popupctrl" href="usercp.php{vb:raw session.sessionurl_q}">{vb:rawphrase your_notifications}: <span class="notifications-number"><strong>{vb:raw notifications_total}</strong></span></a>
<ul class="popupbody popuphover">
{vb:raw notifications_menubits}
</ul>
</li>
<vb:else />
<li class="popupmenu nonotifications" id="nonotifications">
<a class="popupctrl" href="usercp.php{vb:raw session.sessionurl_q}">{vb:rawphrase your_notifications}</a>
<ul class="popupbody popuphover">
<li>{vb:rawphrase no_new_messages}</li>
<li><a href="private.php{vb:raw session.sessionurl_q}">{vb:rawphrase inbox}</a></li>
</ul>
</li>
</vb:if>

Basically, what i am trying to achieve is moving the notifications from header to my new template.

Thanks
B

clubvr4
28 Feb 2012, 15:31
Progressing from my previous query.

I need to register some variables to allow notifications to be registered in my plugin (Post # 216)

I've tried following this guide here..

https://www.vbulletin.com/forum/showthread.php/360905-How-can-I-change-the-notifications-menu-place

I attempted the following, to no avail.

Plugin name = memberbar_member_basic
Plugin Hook = Parse Templates
Plugin Content =
$templater = vB_Template::create('memberbar_member_basic');
$memberbar_member_basic = $templater->render();vB_Template::preRegister('navbar', array('notifications_menubits' => $notifications_menubits));
vB_Template::preRegister('navbar', array('memberbar_member_basic' => $memberbar_member_basic));
vB_Template::preRegister('navbar', array('notifications_menubits' => $notifications_menubits));

I then moved the notifications code from header to the memberbar_member_basic template, which for reference makes the dropdown appear but does not show notifications nor total notifications.

Code moved.

<vb:if condition="$notifications_total">
<li class="popupmenu notifications" id="notifications">
<a class="popupctrl" href="usercp.php{vb:raw session.sessionurl_q}">{vb:rawphrase your_notifications}: <span class="notifications-number"><strong>{vb:raw notifications_total}</strong></span></a>
<ul class="popupbody popuphover">
{vb:raw notifications_menubits}
</ul>
</li>
<vb:else />
<li class="popupmenu nonotifications" id="nonotifications">
<a class="popupctrl" href="usercp.php{vb:raw session.sessionurl_q}">{vb:rawphrase your_notifications}</a>
<ul class="popupbody popuphover">
<li>{vb:rawphrase no_new_messages}</li>
<li><a href="private.php{vb:raw session.sessionurl_q}">{vb:rawphrase inbox}</a></li>
</ul>
</li>
</vb:if>

Basically, what i am trying to achieve is moving the notifications from header to my new template.

Thanks
B

Easy5s.net
23 Mar 2012, 10:00
OK, I have done.

Preech
04 Apr 2012, 08:04
$statar = $db->query_read("SELECT * FROM " . TABLE_PREFIX ." stats");
$templater = vB_Template::create('vbmusic');
$templater->register_page_templates();
$templater->register('navbar', $navbar);
$templater->register('statar', $statar);
print_output($templater->render());

I understand everything. For some reason, I only get the word Array to show up on my templates. This is what I use on my template.
{vb:raw statar}

I'm guessing I have the array register proper. Is there anything else that I have to add to go with the query. I used the * because their is more than just one result to show from that particular table.

cellarius
04 Apr 2012, 08:25
Well, obviously $statar is an array. I have no idea how you set it up, but just as you can't do echo $array in PHP, you can't just use {vb:raw array}. In PHP you would do echo $array['key'] to output the value. In the template you need to use {vb:raw array.key} accordingly.

Just as described in the first chapter of the article.

Preech
05 Apr 2012, 17:20
Appreciate it Cellarius.
I looked through some of the other vbulletin, so I had to do something like.

while yada yada
{ something = something['']}

And everything started working. Mental error on my part. The only thing now is trying to complete a new mod for vbulletin.

Merriweather
22 Apr 2012, 20:12
If anyone is able to guide me, I am trying to hack the Post Thanks Plugin so I can pass a variable to a template as a conditional.

Here is the function I need to create a conditional for:

function can_thank_this_post($postinfo = array(), $threadisdeleted = 0, $check_security = false, $securitytoken = '')
{
global $vbulletin;

($hook = vBulletinHook::fetch_hook('post_thanks_function_can_thank_this_post_start')) ? eval($hook) : false;

if ($postinfo['postid'] == 0 || $vbulletin->userinfo['userid'] == 0 || $postinfo['isdeleted'] || $threadisdeleted || (!($vbulletin->options['post_thanks_poster_button']) && $postinfo['userid'] == $vbulletin->userinfo['userid']))
{
return false;
}

if (post_thanks_in_array($vbulletin->userinfo['usergroupid'], $vbulletin->options['post_thanks_usergroup_using']) || post_thanks_in_array($vbulletin->userinfo['userid'], $vbulletin->options['post_thanks_user_useing']))
{
return false;
}

if ($vbulletin->userinfo['posts'] < $vbulletin->options['post_thanks_post_count_needed'])
{
return false;
}

if ($vbulletin->options['post_thanks_max_per_day'])
{
global $count_thanks_so_far_totay;

if ($count_thanks_so_far_totay === null)
{
$count_thanks_so_far_totay = $vbulletin->db->query_first("SELECT COUNT(*) AS total FROM " .TABLE_PREFIX. "post_thanks WHERE userid = " . $vbulletin->userinfo['userid'] . " AND date > " . (TIMENOW - (60 * 60 * 24)) . "");
}

if ($vbulletin->options['post_thanks_max_per_day'] <= $count_thanks_so_far_totay['total'])
{
return false;
}
}

if ($vbulletin->options['post_thanks_days_old'])
{
if (TIMENOW > (($vbulletin->options['post_thanks_days_old'] * 60 * 60 * 24) + $postinfo['dateline']))
{
return false;
}
}

if ($vbulletin->options['post_groans_integrate'])
{
require_once(DIR . '/includes/functions_post_groans.php');
if (groaned_already($postinfo))
{
return false;
}
}

if ($check_security && function_exists(verify_security_token))
{
if (!verify_security_token($securitytoken, $vbulletin->userinfo['securitytoken_raw']))
{
return false;
}
}

($hook = vBulletinHook::fetch_hook('post_thanks_function_can_thank_this_post_end')) ? eval($hook) : false;

return true;
}

And I want to be able to use:

<vb:if condition="$post['can_thank_post']">Button code here</vb:if>

anupam_luv
25 Apr 2012, 00:37
LW (linkworth ) has given me a php file to include in the navigation bar. It will show rotating ads via rss feed. How can I include that file

I wrote the following code in global_start



ob_start();
include('rss_reader.php');
$linkmura = ob_get_contents();
ob_end_clean();

$templater = vB_Template::create('mytemplate');
$templater->register('my_var', $linkmura);

$templatevalues['linkmura1'] = $templater->render();
vB_Template::preRegister('navbar', $templatevalues);



And using {vb:raw linkmura1} to show that. But nothing is been shown (on navbar http://www.dstreetdirect.com )

Also the code in the rss_reader.php is :



<?php
$insideitem = false;
$tag = "";
$title = "";
$description = "";
$link = "";

function startElement($parser, $name, $attrs)
{
global $insideitem, $tag, $title, $description, $link;

if($insideitem)
{
$tag = $name;
}
elseif($name == "ITEM")
{
$insideitem = true;
}
}

function endElement($parser, $name)
{
global $insideitem, $tag, $title, $description, $link;

if ($name == "ITEM")
{
printf("<dt><b><a href='%s' title='%s'>%s</a></b></dt>",
trim($link),htmlspecialchars(trim($description)),htmlspecialchars(trim($title))) ;
printf("<dt>%s</dt><br/><br/>",htmlspecialchars(trim($description)));

$title = "";
$description = "";
$link = "";
$insideitem = false;
}
}

function characterData($parser, $data)
{
global $insideitem, $tag, $title, $description, $link;

if($insideitem)
{
switch($tag)
{
case "TITLE":
$title .= $data;
break;
case "LINK":
$link .= $data;
break;
case "DESCRIPTION";
$description .= $data;
break;
}
}
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");

//====================================================================
//====================================================================
//====================================================================
// ENTER YOUR UNIQUE RSS URL BELOW WHERE YOU SEE THE XXXX's
//====================================================================
//====================================================================
//====================================================================
$fp = fopen("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "r")
or die("Error reading RSS data.");


while ($data = fread($fp, 4096))
xml_parse($xml_parser, $data, feof($fp))
or die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
fclose($fp);
xml_parser_free($xml_parser);

?>



Please smbdy help and tell me easiest way to do that....

Dax IX
25 Apr 2012, 02:33
I'm just curious if registering the navbar is always necessary if you're creating a template for your own vB page, and if so, should the first post be updated to illustrate this?

And where the hell is the documentation on things like this:

Try this in the parse_templates hook:

require_once(DIR . '/includes/class_template_parser.php');
$parser = new vB_TemplateParser('<div id="toplinks" class="toplinks">');
$parser->dom_doc = new vB_DomDocument($parser->fetch_dom_compatible());
$find = trim($parser->_parse_nodes($parser->dom_doc->childNodes()));

$parser = new vB_TemplateParser('<div style="float:right; margin: 5px -12px 5px 10px;">{vb:raw mycode}</div>');
$parser->dom_doc = new vB_DomDocument($parser->fetch_dom_compatible());
$replace = trim($parser->_parse_nodes($parser->dom_doc->childNodes()));

$vbulletin->templatecache['header'] = str_replace($find, $find . $replace, $vbulletin->templatecache['header']);
unset($find, $replace);

Or do you have to go through all the various files yourself to learn all of the functions and hope you stumble on what you're looking for?

Boofo
25 Apr 2012, 16:14
You won't stumble on to that anywhere in the files. ;)

Easy5s.net
28 Apr 2012, 10:26
Pls help me :(
http://www.vbulletin.org/forum/showthread.php?t=282142

Seductor
15 May 2012, 00:52
If I have this:
$my_array = array(1,2);

How can I render my template in order to show it? I don't know which key it is being used. If I do this:
{vb:raw my_array}

It is rendered like:
Array

PS: By the way, do you know any tutorial about how to send queries to the database from vBulletin?

BirdOPrey5
15 May 2012, 02:41
{vb:raw my_array.0} = 1
{vb:raw my_array.1} = 2

cellarius
15 May 2012, 07:11
If I have this:
$my_array = array(1,2);

How can I render my template in order to show it? I don't know which key it is being used. If I do this:
{vb:raw my_array}

It is rendered like:
Array
See the article:
{vb:raw my_var}
{vb:raw my_array.key1}

PS: By the way, do you know any tutorial about how to send queries to the database from vBulletin?
http://www.vbulletin.org/forum/showthread.php?t=119350

Seductor
15 May 2012, 11:36
Oh, and is there any way to show all my array cells If I don't know which size is the array?

Edited: I suspect that it is done in this way.
<vb:each from="my_array" key="key1" value="my_result">
{vb:var my_result}
</vb:each>


I am doing something wrong. I have this:
resource(46) of type (mysql result)

And each row is:
array(21) { ["id"]=> string(2) "18" ["name"]=> string(5) "ABRIR" ["description"]=> string(23) "Iniciar la interacción." ["userid"]=> string(4) "2858" ["username"]=> string(20) "Seducción Científica" ["dateline"]=> string(10) "1311875182" ["lastupdate"]=> string(10) "1311933838" ["categoryid"]=> string(1) "1" ["status"]=> string(1) "1" ["ipaddress"]=> string(13) "81.202.205.41" ["attach"]=> string(1) "0" ["threadid"]=> string(1) "0" ["lastupdater"]=> string(20) "Seducción Científica" ["lastupdaterid"]=> string(4) "2858" ["tags"]=> string(16) "abrir,escalada 1" ["popup"]=> string(23) "Iniciar la interacción." ["views"]=> string(1) "0" ["votenum"]=> string(1) "0" ["votetotal"]=> string(1) "0" ["linkurl"]=> string(7) "http://" ["banner"]=> string(7) "http://" }

I'm doing this in my template:

<vb:each from="my_query" value="sentence">
Test {vb:raw sentence.name}
</vb:each>


Notice this: Test {vb:raw sentence.name}

But It doesn't show nothing, as if the each is not being executed. I expected to show, at least, 46 Test words.

kh99
15 May 2012, 14:52
I am doing something wrong. I have this:
resource(46) of type (mysql result)


You are registering the return from one of the query functions. You need to call fetch_array() to get an array for each row, like:

$results = $db->query_read("some sql");
while ($row = $db->fetch_array($results))
{
// do something with $row
}


Of course each row is an array (even if you only selected one column). If you are selecting one column from a number of matching rows, you won't get an array with all the matching values, you still get an array for each row. If you want an array with all the matching values you'd have to build that yourself.

Note also that you don't *have* to register an array to your template and use vb:each - you could format your own html string in the while loop above, then just register the string.

tbworld
26 May 2012, 21:20
[QUOTE=Boofo;2287132]Try this in the parse_templates hook:

Boofo, I was working on specialized routine and trying to use some of the vb-ojects to solve my problem when I came across the code you posted here. This redirected me to the right vb routines. Thanks so much for sharing!

Dave-ahfb
26 May 2012, 22:11
I have a problem on a page. I can use the variable {vb:raw companyname} in the places of the template that I need to. However when I want to place it in my navbits which are created by the php file it just echos itself.
$navbits = construct_navbits(array('' => '&nbsp;</span></li><li class="navbit"><span><a href="/">Home</a></span></li><li class="navbit"><span><a href="../hostindex.php">Web Hosting</a></span></li><li class="navbit lastnavbit"><span>{vb:raw companyname}

'));
$navbar = render_navbar_template($navbits);

// ###### YOUR CUSTOM CODE GOES HERE #####
$pagetitle = '$companyname';
$templater = vB_Template::create('headerincludea');
$headerincludea = $templater->render();

$templater = vB_Template::create('webhost-php');
$templater->register('companyname', $companyname);
$templater->render();



$templater->register_page_templates();
$templater->register('navbar', $navbar);
$templater->register('pagetitle', $pagetitle);
$templater->register('headerincludea', $headerincludea);


print_output($templater->render());

kh99
26 May 2012, 22:43
Try putting $companyname in your navbits instead of {vb:raw companyname} Since it's in a single-quoted string you need to use concatenation, like:

$navbits = construct_navbits(array('' => '&nbsp;</span></li><li class="navbit"><span>
<a href="/">Home</a></span></li><li class="navbit"><span>
<a href="../hostindex.php">Web Hosting</a></span></li>
<li class="navbit lastnavbit"><span>' . $companyname . '

'));

Dave-ahfb
26 May 2012, 22:57
Try putting $companyname in your navbits instead of {vb:raw companyname} Since it's in a single-quoted string you need to use concatenation, like:

$navbits = construct_navbits(array('' => '&nbsp;</span></li><li class="navbit"><span>
<a href="/">Home</a></span></li><li class="navbit"><span>
<a href="../hostindex.php">Web Hosting</a></span></li>
<li class="navbit lastnavbit"><span>' . $companyname . '

'));

Thanks a ton! I had tried $companyname without the '. .' and had the same results (echoed $companyname.

Chr1sj
31 May 2012, 13:57
Can anyone help me out what i'm doing wrong?

i'm trying to add something to the Default navbar template. (a server status for my game server)
but first i'm trying out the example but i can't get it to work.

This is my plugin setup.
Product : vBulletin
Hook location: Global_start
Title: server Status
execution order :5

Plugin code:
/* Some Code, setting variables, (multidimensional) array */
$my_var = "abc";

/* render template and register variables */
$templater = vB_Template::create('navbar');
$templater->register('my_var', $my_var);
$templater->render();

Then in the navbar template of my default style i add {vb:raw my_var}
even tried withing <p>{vb:raw my_var}</p>

Anyone able to help me out ?

Edit: and Enable Plugin/Hook System is enabled also

kh99
31 May 2012, 14:02
You don't want to render the navbar template because the vbulletin code already does that for you. To get your variable registered to that template you want to use preRegister, like;


$my_var = "abc";
vB_Template::preRegister('navbar', array('my_var' => $my_var));

Chr1sj
31 May 2012, 14:28
Thanks a lot. :up:
Now i can start creating my plugin understanding the preRegister.

codewaggle
10 Jun 2012, 10:41
I have a template that I need to insert into multiple pre-existing templates. After a bit of struggling, I have managed to get the following code running.

$templater = vB_Template::create('layout_start');
$templater->register('my_var', $my_var);
$templatevalues['start_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME', $templatevalues);

I have two questions. Is there any way to preRegister for more than one pre-existing template (or a global registration), or do I have to create Plugins for every page I want to add this to (*groan*)? And what is the best hook to have this on. I am currently using 'parse_templates'.

------------------------------------

I'm doing this using $GLOBALS[templatevalues] = $templatevalues; rather than preRegister().


$templater = vB_Template::create('layout_start');
$templater->register('my_var', $my_var);
$templatevalues['start_insertvar'] = $templater->render();

$GLOBALS[templatevalues] = $templatevalues;

UPDATE: (Thanks to kh99 (http://www.vbulletin.org/forum/member.php?u=346440) for his guidance.)
The following line isn't needed and was used incorrectly:
$template->register_global('templatevalues');



Then use this in the templates where you want the output to appear:

{vb:raw GLOBALS.templatevalues.start_insertvar}


Be Well

Craigr
20 Jul 2012, 16:07
I am creating a custom mod for my site, at the moment i have done this and only get a white page displayed, but at least the result appears. I am not sure what example to follow so that the rest of the showthread template appears too?

Plugin:
Product: vBulletin
Hook Location: showthread_post_start
Title: galleryimagedisplay
Execution Order: 5
PHP Code:

$result = $db->query_first("SELECT * FROM dbtech_gallery_images WHERE roll_id = '$threadid'");
$id = $result[imageid];
$title = $result[title];

$templater = vB_Template::create('test');
$templater->register('id', $id);
$templater->register('title', $title);
$templatevalues['my_insertvar'] = $templater->render();
vB_Template::preRegister('SHOWTHREAD', $templatevalues);


This is my template:

{vb:raw id} {vb:raw title}


Edit: Got the above displaying ok now.

BirdOPrey5
20 Jul 2012, 16:46
off hand it's vb:raw in the templates, not vbraw: and there is no $ either.

Test Text: {vb:raw id} {vb:raw title}

Steve St.Lauren
04 Aug 2012, 02:06
I'm trying to use several of my user custom fields on a page in profile.php. I've got the template working and the page is displaying ok but I can't get the custom fields to display. I've tried a ton of stuff and just can't get it to work - would GREATLY appreciate any help you could provide. Here's what I'm doing now. This is the plug in code going into profile.php:

if ($_REQUEST['do'] == 'showsubscription')
{
echo 'test';
$customfields = array();
fetch_profilefields(0);
$page_templater = vB_Template::create('showsubscription');
$page_templater->register('customfields', $customfields);
}

in the template itself I'm putting in:

{vb:raw customfields.value11}

where I want to use the field. I've also tried customfields.field11 various permutation of userinfo, userfield, etc. I was able to do this in vb3 no problem but having a tough time getting it to work in vB4.

BirdOPrey5
04 Aug 2012, 10:36
Do you have the working 3.x code?

Steve St.Lauren
04 Aug 2012, 22:59
Yes, in VB3 it was very easy - all I had to do was put $bbuserinfo[field11] on the template. The plugin portion of it was:

// ############################ start show subscription info ##########################
if ($_REQUEST['do'] == 'showsubscription')
{
construct_usercp_nav('showsubscription');

$navbits[''] = 'Subscription Status';
$templatename = 'showsubscription';
$url =& $vbulletin->url;
}

BirdOPrey5
05 Aug 2012, 12:34
I'm sorry, either I don't understand what you are trying to do or are missing something big.

Steve St.Lauren
05 Aug 2012, 20:24
I have a number of custom user fields created and I want for the values of those fields to appear on a profile page. In this case it's a subscription status page that lets the user know when their subscription expires and how many issues they have left remaining on their subscription. In VB3 the profile.php page had $bbuserinfo loaded with those fields and they could be called simply by putting $bbuserinfo[field11] in the template - it would put the value there.

showsubscription was the name of the custom template that I created and it would appear along with all of the profile page navigation around it. I have the showsubscription template appearing in vb4 now but I can't get the values of the custom fields to appear on the page. I'm pretty sure it will involve the {vb raw} function and registering a variable for it to be able to appear in the template but just can't figure it out. profile.php must already be loading the custom user fields somewhere because it's used elsewhere on the page.

PyroChixRock
13 Aug 2012, 00:39
I have this little random banner code I've always used through the plugin system, but I can't seem to get it to work on vb4. Can anyone help?

normally, I call for it below the navbar with this...<br>
<div style="text-align: center;">
$randombanner
</div>

and this for example, in the plugin area. $path = '/forum/images/adbanners/';
$banners = array(
array( 'src' => 'imagine.jpg',
'href' => 'http://www.talkglass.com/'),
array( 'src' => 'waiting.jpg',
'href' => 'http://www.talkglass.com/),
);


$rnd = rand(0,count($banners)-1); // Pick a random array index. They start with 0, so you have to -1.
$href = $banners[$rnd]['href']; // Link HREF
$src = $path.$banners[$rnd]['src']; // Image source
$randombanner = '<a href="'.$href.'"><img border="0" src="'.$src.'" /></a>';

Where should i plug these in now for them to work with the built in ad system. it doesn't work using that.

kh99
13 Aug 2012, 14:13
Where should i plug these in now for them to work with the built in ad system. it doesn't work using that.


Try using hook parse_templates and at the end of your plugin code add:
vB_Template::preRegister('navbar', array('randombanner' => $randombanner));


Then in the navbar template, use this:
<br>
<div style="text-align: center;">
{vb:raw randombanner}
</div>

PyroChixRock
13 Aug 2012, 19:59
Thanks, Kevin. I really appreciate you taking the time to reply.

It seems I have everything right but it's not showing up.

I'm not sure what else to do but this is the last thing I need before I can go live with my upgrades. VB is no help because it's custom code.

I'm not sure what else to tell you that would be helpful? Would you be willing to hop over to my test forum and have a look? If so send me a pm and I'll give you login info.