Go Back   vb.org Archive > vBulletin Article Depository > Read An Article > vBulletin 4 Articles
FAQ Community Calendar Today's Posts Search

Reply
 
Thread Tools
[HOW TO - vB4] Rendering templates and registering variables - a short guide
cellarius's Avatar
cellarius
Join Date: Aug 2005
Posts: 1,987

 

Show Printable Version Email this Page Subscription
cellarius cellarius is offline 11-15-2009, 10:00 PM

Introduction

Starting with vB4, templates no longer get output using eval:
PHP Code:
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

PHP Code:
/* 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:
HTML Code:
{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


PHP Code:
$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:
PHP Code:
$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


PHP Code:
$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
PHP Code:
$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:
PHP Code:
$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
HTML Code:
{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

PHP Code:
$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:
HTML Code:
{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:
PHP Code:
$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:
PHP 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...in-4-templates
http://www.vbulletin.com/forum/entry...-4-based-files
Reply With Quote
  #182  
Old 07-26-2011, 05:30 PM
cellarius's Avatar
cellarius cellarius is offline
 
Join Date: Aug 2005
Posts: 1,987
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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.
Reply With Quote
  #183  
Old 08-04-2011, 03:50 AM
EquinoxWorld EquinoxWorld is offline
 
Join Date: Nov 2009
Location: Naples
Posts: 354
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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 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.
Reply With Quote
  #184  
Old 08-04-2011, 04:14 AM
MikeF MikeF is offline
 
Join Date: Jan 2006
Posts: 40
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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?
Reply With Quote
  #185  
Old 08-05-2011, 08:12 PM
kh99 kh99 is offline
 
Join Date: Aug 2009
Location: Maine
Posts: 13,185
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by MikeF View Post
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:

Code:
$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
HTML Code:
{vb:raw random_number}
Reply With Quote
  #186  
Old 08-14-2011, 11:40 PM
RobDog888's Avatar
RobDog888 RobDog888 is offline
 
Join Date: Apr 2007
Location: Degabah Swamp
Posts: 293
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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...

Code:
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
Reply With Quote
  #187  
Old 08-15-2011, 06:59 AM
cellarius's Avatar
cellarius cellarius is offline
 
Join Date: Aug 2005
Posts: 1,987
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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:
Code:
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.
Reply With Quote
  #188  
Old 08-16-2011, 03:30 AM
RobDog888's Avatar
RobDog888 RobDog888 is offline
 
Join Date: Apr 2007
Location: Degabah Swamp
Posts: 293
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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
Reply With Quote
  #189  
Old 08-17-2011, 01:40 PM
demo7up demo7up is offline
 
Join Date: Apr 2007
Posts: 92
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by moonray View Post
FINAL WORKING CODE:

Product: vBulletin
Title: Insert Simple PHP
Execution order: 5
Hook Location: global_start
PHP code:
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
Code:
{vb:raw insert_simple_php}
just under the code
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

Code:
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

Code:
{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 [DATE]1313595423[/DATE] at [TIME]1313595423[/TIME] ---------------

Quote:
Originally Posted by demo7up@gmail.c View Post
Im trying to use this code to include a php file in my custom page this is what im using

Code:
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

Code:
{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.
Reply With Quote
  #190  
Old 08-18-2011, 11:38 PM
HMBeaty's Avatar
HMBeaty HMBeaty is offline
 
Join Date: Sep 2005
Posts: 4,141
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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
PHP Code:
$templater vB_Template::create('usml_military_ranks_sidebar');
$usml_military_ranks_sidebar $templater->render();
vB_Template::preRegister('usml_military_ranks',array('usml_military_ranks_sidebar' => $usml_military_ranks_sidebar)); 
Template
I'm calling my sidebar template in my template usml_military_ranks (and many others) by using:
Code:
{vb:raw usml_military_ranks_sidebar}
PHP file
In the PHP file for usml_military_ranks I have:
PHP Code:
    $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
Reply With Quote
  #191  
Old 08-19-2011, 12:07 AM
kh99 kh99 is offline
 
Join Date: Aug 2009
Location: Maine
Posts: 13,185
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

You might try taking this line out of the php file:

PHP Code:
$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.
Reply With Quote
Благодарность от:
HMBeaty
Reply


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 02:09 AM.


Powered by vBulletin® Version 3.8.12 by vBS
Copyright ©2000 - 2024, vBulletin Solutions Inc.
X vBulletin 3.8.12 by vBS Debug Information
  • Page Generation 0.05377 seconds
  • Memory Usage 2,400KB
  • Queries Executed 26 (?)
More Information
Template Usage:
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_header_end
  • (1)ad_header_logo
  • (1)ad_navbar_below
  • (1)ad_showthread_beforeqr
  • (11)bbcode_code
  • (4)bbcode_html
  • (13)bbcode_php
  • (3)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)modsystem_article
  • (1)navbar
  • (4)navbar_link
  • (120)option
  • (1)pagenav
  • (1)pagenav_curpage
  • (4)pagenav_pagelink
  • (2)pagenav_pagelinkrel
  • (11)post_thanks_box
  • (18)post_thanks_box_bit
  • (11)post_thanks_button
  • (1)post_thanks_javascript
  • (1)post_thanks_navbar_search
  • (2)post_thanks_postbit
  • (11)post_thanks_postbit_info
  • (10)postbit
  • (11)postbit_onlinestatus
  • (11)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available:
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files:
  • ./showthread.php
  • ./global.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/class_hook.php
  • ./includes/modsystem_functions.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_post_thanks.php 

Hooks Called:
  • init_startup
  • init_startup_session_setup_start
  • init_startup_session_setup_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • style_fetch
  • cache_templates
  • global_start
  • parse_templates
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • forumjump
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • post_thanks_function_post_thanks_off_start
  • post_thanks_function_post_thanks_off_end
  • post_thanks_function_fetch_thanks_start
  • fetch_musername
  • post_thanks_function_fetch_thanks_end
  • post_thanks_function_thanked_already_start
  • post_thanks_function_thanked_already_end
  • post_thanks_function_fetch_thanks_bit_start
  • post_thanks_function_show_thanks_date_start
  • post_thanks_function_show_thanks_date_end
  • post_thanks_function_fetch_thanks_bit_end
  • post_thanks_function_fetch_post_thanks_template_start
  • post_thanks_function_fetch_post_thanks_template_end
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • post_thanks_function_can_thank_this_post_start
  • pagenav_page
  • pagenav_complete
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • showthread_complete