sFire PHP Framework

Template engine: Variables

Using variables in your view is necessary to make it dynamic. You may want to show the current logged in username or use a PHP function. To do so, you may use the variable parser from the built-in template engine.

Using variables

To use variables in the view, you need to assign them in your controller:

using sFire\MVC\ViewModel;

$view = new ViewModel('home.index');
$view -> assign('foo', 'bar');

Now you can use the foo variable in you view like:

{{ $foo }}

This way, the variable will be automatic be escaped with htmlentities.

You can overwrite this default behavior like:

{- $foo -}

This way the variable won't be escaped, so be careful using this option.

You can also use the variables for other template functions like if statements:

@if($foo === 'bar')
    foo equals bar
@endif

*Note: you won't have to use the {{ }} (curly brackets) around the variables to use them in other template functions.

To use PHP functions in your view, you can call them like:

{{ date('H:i:s') }} //Output similar to: 12:52:08

Escaping

Variables like {{ $foo }} will automatically be escaped as HTML. But this is not the holy grail for escaping your data.

Escaping variables is very important. Thats why sFire template engine has built-in features for escaping them to prevent XSS attacks.

There are five types of variables. HTML, CSS, Javascript, HTML attribute values and Url's which you should escape depending on the context where the variable will be outputted.

@escape($value, 'html')
@escape($value, 'css')
@escape($value, 'url')
@escape($value, 'js')
@escape($value, 'attr')

A few examples

//HTML: 
@escape('<script>alert(1);</script>', 'html');

//Javascript
<a href="@escape('javascript:alert(1);', 'js')">test</a>
<a href="@escape('"><script>alert(1);</script>', 'js')">test</a>

Note: Keep in mind that URL escaping is ment to escape a part of an URL. This is a wrapper method for PHP's rawurlencode.