Note: each tutorial contains information about one specific part of Spoon. If something is unclear, post a comment.

Template - part 1

Written by Davy Hellemans -

Prerequisites

What will you learn?

  • Load and display templates
  • Assign variables
  • Simplified if/else control structures

Tutorial

Template basics

Templates provide a great way to separate code from layout. You can compare it to inline style attrbutes in HTML versus CSS files. Another great advantage is that designers don't need to know PHP to be able to modify or create templates.

SpoonTemplate applies a common used technique to compile its' templates to PHP code. This is done to speed up the actual displaying of templates.

Assigning variables

The 3 most important things in the template are: assigning variables, optional blocks and iterating arrays. In this tutorial we'll only be going over the first 2.

In the example below, 2 values are assigned to a template. You can then use those 2 variables in the template code. There's no limit on the number of times you can use a template variable.

// required classes
require_once 'spoon/spoon.php';

/* contents of our template.tpl file:
My name is {$name} and I live in {$city}.
*/

// load template
$tpl = new SpoonTemplate();

/*
 * Should this template be recompiled to PHP every time you execute this
 * PHP script. This is encouraged to be enabled during development, since
 * changes to your template file won't be visible otherwise.
 */
$tpl->setForceCompile(true);

/*
 * By default, the compiled templates will be stored in the directory
 * wherein your PHP script resides. Since this is nasty, we advise you
 * to choose a good location where these files may be stored.
 */
$tpl->setCompileDirectory('/home/my_project/compiled_templates');

// assign some variables
$tpl->assign('name', 'Davy Hellemans');
$tpl->assign('city', 'Gent');

// show the output, using 'template.tpl'
$tpl->display('template.tpl')

This example gives the following output.

My name is Davy Hellemans and I live in Gent.

Optional elements

Options are optional elements, based on the assigned variables. Each variable is also available as an option in your template. If the value of this variable is not empty or false, it's considered true and allows for simple if/else structures. Inverse options are also available, considering the value of your variable results to false. The syntax of both these options is very similar, except for the exclamation mark. Just as with variables, there's no limit on the amount of times you can use an option. Also note that options may even be nested.

// required classes
require_once 'spoon/spoon.php';

/* contents of our template.tpl file:
Name: {$name}
City: {$city}
{option:email}E-mail: {$email}{/option:email}

{option:!email}Woops, we don't know your e-mail{/option:!email}
*/

// load template
$tpl = new SpoonTemplate();

// force compiling
$tpl->setForceCompile(true);

// choose compile directory
$tpl->setCompileDirectory('/home/my_project/compiled_templates');

// assign some variables
$tpl->assign('name', 'Davy Hellemans');
$tpl->assign('city', 'Gent');
$tpl->assign('email', 'davy@spoon-library.be');

// show the output, using 'template.tpl'
$tpl->display('template.tpl')

This example gives the following output.

Name: Davy Hellemans
City: Gent
E-mail: davy@spoon-library.be

If we wouldn't have assigned a value for 'email', then the inverse option would be shown, providing the following output:

Name: Davy Hellemans
City: Gent

Woops, we don't know your e-mail

Conclusion

You can now assign values to variables in an easy way. Of course there's more, but this is just an introduction. The upcoming tutorial concerning SpoonTemplate will show you how to iterate over variables in templates.

31 comments

Arnout wrote 2 years ago

How can I make a simple if/else condition like this one:
{if $alpha == 'Test'}
<p>Test it, baby!</p>
{elseif $beta == 'No test'}
<p>Sorry, no testing!</p>
{else}
<p>Damn, what's this!</p>
{/if}

Thx!

Bauffman wrote 2 years ago

@Arnout
In the current version of the template engine it's not possible to use an explicit if/else condition. At this time you're only able to use predefined if/else conditions from your code. You'd have to do something like this:

$tpl->assign('alpha', $alpha == 'test');
$tpl->assign('beta', $beta == 'no test');

And your template could look like this:
{option:alpha}
<p>Test it, baby!</p>
{/option:alpha}
{option:!alpha}
{option:beta}
<p>Sorry, no testing!</p>
{/option:beta}
{/option:!alpha}

It's for that reason the template engine syntax is being reworked at this moment. In the future it will probably look like this, giving you more specific clausules in your template files:

{if $alpha == 'Test'}
<p>Test!</p>
{elseif $beta == 'No test'}
<p>Sorry, no testing</p>
{else}
<p>Damn, what is this?</p>
{endif}

Guillermo wrote 2 years ago

Hi, There i's a {include} tag for contents that doesn't change such as footer, header, menu ... Thanks!

Bauffman wrote 2 years ago

@guillermo Yes, there is an include tag:

{include:location/of/my/footer.tpl}

Michal wrote 2 years ago

is it possible to somehow get the number of iteration?

Bauffman wrote 2 years ago

@michal
What do you mean by 'the number of iteration'? I assume you want to know within the loop which item that is? Something like:

{iteration:dogs}
{$dogs.number} - {$dogs.name}
{/iteration:dogs}

Lun wrote 2 years ago

{iteration:dogs}
{iteration:cats}
{if $dogs.number == $cats.id}
<p> {$cats.id}</p>
{elseif $beta == 'No test'}
<p>Sorry, no testing</p>
{else}
<p>Damn, what is this?</p>
{endif}
{/iteration:dogs}

like this,how do it。

Bauffman wrote 2 years ago

@lun
What you want to do is currently not possible. At this time you can't use if/else clausules within the template engine.

Lun wrote 2 years ago

I want to know in a few versions will add it( if/else) this feature?

Bauffman wrote 2 years ago

@lun there's going to be a new template component around december/january. That will have the if/else clausules and much more.

Lun wrote 2 years ago

@Bauffman good~O(∩_∩)O 谢谢!

Koen Vinken wrote 2 years ago

I'm also looking forward to the new if/else clausules. It should make things a bit easier. But for now I was able to do it with options. For example. If I have an array I slice certain parts of the array and use options (like Bauffman explained) to fake if/else conditions.

One question though. Will the new if/else clausule also work with iterations? Something like this:

{iteration:dogs}
{if $dogs.Name== 'Timmy'}
<p>Hello, this is Timmy!</p>
{elseif $dogs.Name== 'Buddy'}
<p>Hello, this is Buddy!</p>
{else}
<p>I don't know who I am!</p>
{endif}
{/iteration:dogs}

Bauffman wrote 2 years ago

@koen
In the new syntax that would look like this:
{for $dog in $dogs}
    {if $dog.name == 'Timmy'}
        <p>Hello, this is Timmy!</p>
    {elseif $dog.name == 'Buddy'}
        <p>Hello, this is Buddy!</p>
    {else}
        <p>I don't know who I am!</p>
    {endif}
{endfor}

Koen Vinken wrote 2 years ago

Aha, got it. Looking forward to it!

Francois de Kort wrote 2 years ago

Is there any particular reason why you can't access the last level off an array directly if it has numeric key? I mean template code like {$a.b} works perfectly if $a contains an array with a key 'a', {$a.1.b} also works with the correct array, but code like {$a.1} or {$a.b.2} doesn't. It gives a notice in compiler.php when SPOON_DEBUG is defined, and doesn't substitute the value.

Stijn Eckeman wrote 2 years ago

Does anyone know if it's possible to let html in variables been rendered?
so when $myvar = '1<sup>st</sup> year';
Then I have in my template {$myvar}, but this gets shown as "1<sup>st</sup> year".
So my question, is it possible that the html gets rendered instead of being shown as is.

Bauffman wrote 2 years ago

@stijn are you using the latest beta template component or spoon library v1.3?

Stijn Eckeman wrote 2 years ago

@Bauffman: I'm using the standalone component (from https://github.com/Spoon/Template ) because I wanted the ability to use {if} statements etc.

Bauffman wrote 2 years ago

In the evironment you can disable 'auto_escape'. Then your output will not be escaped.
$environment->disableAutoEscape();

Stijn Eckeman wrote 2 years ago

Works like a charm! thx man!

P.S.: I can't post a message here unless I press 'Edit my comment settings' and remove the 'pre filled in' http:// for Website (since I didn't filled this in the first time) ;)

Dominik wrote 2 years ago

@Stijn I would like to be able to use the standalone component (SpoonTemplate) for the same reason as yours. How did you implement this? Any help would be appreciated. Thank you.

Stijn Eckeman wrote 2 years ago

@Dominik: I put the standalone Template code in the existing Template folder of the Spoon library (removed all existing files).

Simple piece of code to get the template function working:
// add spoon to the include path
// note that PATH_SEPARATOR and PATH_FRAMEWORK_LIBRARY are defined constants by myself
set_include_path(get_include_path() . PATH_SEPARATOR . PATH_SPOON_LIBRARY);
// require spoon
require_once 'spoon.php';

// Template framework
require_once 'Spoon/Template/Autoloader.php';
Spoon\Template\Autoloader::register(); // if somebody knows why I just can't use Autoloader::register(); plz let me know ;)
$env_options = Array('auto_escape' => false, 'cache' => PATH_ROOT . 'temp/compiled_templates/', 'auto_reload' => true);
$env = new Spoon\Template\Environment($env_options);
$tpl = new Spoon\Template\Template($env);

// assign some variables here

// show the output
$tpl->render('templates/header.tpl');

// etc...

Stijn Eckeman wrote 2 years ago

@Dominik: there's a basic manual included in the standalone version: https://github.com/Spoon/Template/blob/master/README.md ;)

Bauffman wrote 2 years ago

To all those seeking help. I've set up a forum on tenderapp.com.
My hosting company is still working on the redirect (support.spoon-library.com), but for now you can ask all your questions on http://spoon.tenderapp.com/dashboard

Lorenz Quintens wrote 1 year ago

I get this error when I request one of my php webpages: 'The file "./core/spoon_compiled_templates/121c81af9ea6e420625e0dc519c3a34e_inschrijvingsformulier.tpl.php" could not be created. Check if PHP has enough permissions.'
It occurs in 'file/file.php'.
What permissions do I need to set?

Bauffman wrote 1 year ago

You have to make sure the directory 'spoon_compiled_templates' is writable.

Lorenz Quintens wrote 1 year ago

It was previously chmodded to 774, now I've set it to 777 and it works, but does it need to be that accessible? Can't I set it to a 'lower' level of access?

Bauffman wrote 1 year ago

Yes you can, as long as PHP has write access to that folder.

Lorenz Quintens wrote 1 year ago

On a related note: is it possible to bypass the compiling?

Bauffman wrote 1 year ago

Not at this moment no.

Lorenz Quintens wrote 1 year ago

Some control structures are already available in the standalone template componten. Will those be added to the complete library soon or is there a simple way to achieve this?