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
  #212  
Old 01-13-2012, 05:55 AM
HMBeaty's Avatar
HMBeaty HMBeaty is offline
 
Join Date: Sep 2005
Posts: 4,141
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by Boofo View Post
Try this in the parse_templates hook:

Code:
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 I might have to use this in the future
Reply With Quote
  #213  
Old 01-13-2012, 06:34 AM
Boofo's Avatar
Boofo Boofo is offline
 
Join Date: Mar 2002
Location: Des Moines, IA (USA)
Posts: 15,776
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Go for it. An unnamed dev gave it to me a long while back.
Reply With Quote
  #214  
Old 02-23-2012, 06:18 PM
clubvr4's Avatar
clubvr4 clubvr4 is offline
 
Join Date: Jul 2010
Posts: 116
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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

Quote:
Originally Posted by clubvr4 View Post
The template I want to call from navbar template is called memberbar_basic.
You would create a new plugin with code something like this:

Code:
$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.
Reply With Quote
  #216  
Old 02-27-2012, 09:20 AM
clubvr4's Avatar
clubvr4 clubvr4 is offline
 
Join Date: Jul 2010
Posts: 116
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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 =
PHP Code:
$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
Reply With Quote
  #217  
Old 02-27-2012, 09:24 AM
BirdOPrey5's Avatar
BirdOPrey5 BirdOPrey5 is offline
Senior Member
 
Join Date: Jun 2008
Location: New York
Posts: 10,610
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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.
Reply With Quote
  #218  
Old 02-27-2012, 01:04 PM
clubvr4's Avatar
clubvr4 clubvr4 is offline
 
Join Date: Jul 2010
Posts: 116
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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 [DATE]1330432890[/DATE] at [TIME]1330432890[/TIME] ---------------

--------------- Added [DATE]1330432974[/DATE] at [TIME]1330432974[/TIME] ---------------

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/show...ons-menu-place

I attempted the following, to no avail.

Plugin name = memberbar_member_basic
Plugin Hook = Parse Templates
Plugin Content =
PHP Code:
$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.

PHP Code:
                <vb:if condition="$notifications_total">
                <
li class="popupmenu notifications" id="notifications">
                    <
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">
                    <
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
Reply With Quote
Благодарность от:
BirdOPrey5
  #219  
Old 02-28-2012, 02:31 PM
clubvr4's Avatar
clubvr4 clubvr4 is offline
 
Join Date: Jul 2010
Posts: 116
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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/show...ons-menu-place

I attempted the following, to no avail.

Plugin name = memberbar_member_basic
Plugin Hook = Parse Templates
Plugin Content =
PHP Code:
$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.

PHP Code:
                <vb:if condition="$notifications_total">
                <
li class="popupmenu notifications" id="notifications">
                    <
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">
                    <
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
Reply With Quote
  #220  
Old 03-23-2012, 09:00 AM
Easy5s.net Easy5s.net is offline
 
Join Date: Jun 2011
Posts: 201
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

OK, I have done.
Reply With Quote
  #221  
Old 04-04-2012, 06:04 AM
Preech Preech is offline
 
Join Date: Aug 2002
Location: Fort Campbell
Posts: 325
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

PHP Code:
$statar $db->query_read("SELECT * FROM " TABLE_PREFIX ." stats"); 
PHP Code:
$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.
PHP Code:
{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.
Reply With Quote
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 01:27 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.07966 seconds
  • Memory Usage 2,432KB
  • 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
  • (2)bbcode_code
  • (3)bbcode_html
  • (18)bbcode_php
  • (2)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
  • (1)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