ViewFish Templating

The isset statement

If you want to test the truthiness of a variable — the equivalent of isset() or !empty in PHP — you can use ViewFish's isset syntax. ViewFish's isset test checks if the variable is blank. If it's blank, the result will be removed. If it's set, it will be rendered.

It's important to note the difference between {{isset}} and {{var!}}. If you just want a variable to disappear if it's blank, you can use the exclamation mark or you can set 'replace_empty' to true in your ViewFish options. The {{isset}} statement, however, can optionally show or hide a block of text, more than just the variable itself.

The syntax looks like so:

{{isset $something}}
    I want to eat {{something}}. 
{{/isset}}

You could also use the dollar sign on the variable:

{{isset $something}}
    I want to eat {{$something}}. 
{{/isset}}
Note that in the isset statement, you'll use a dollar sign to indicate the variable for which you are testing. Dollars signs are not necessary in standard templates, but can be used there as well.

In the above, the entire block of text is hidden if $something is not set. When using replace_empty, only the {{$something}} would be stripped.

How do we use the above template? Let's see the PHP:

// prep the data array
$args = [
    'something'=>'brownies'
];

// create the ViewFish object
$t = new  new ViewFish\viewfish('/path/to/templates/');

// load the template 
$template = $t->load_template('template-name.tmpl'); 

// render the template
echo $t->render($template,$args);

The output of the above would be:

I want to eat brownies.

Next, using this template:

Hello, my name is {{$name|ucfirst}} and I am applying for the position of {{$position}}. 
{{if $closing}}{{$closing}}, {{/if}}
{{$name|ucfirst}}

Let's feed it this array:

$args = [
    'name'=>'Adam', 
    'position'=>'Engineer', 
];

Our output would be:

Hello, my name is Adam and I am applying for the position of engineer. Adam

But if we fed it this, with a new element called 'closing':

$args = [
    'name'=>'Adam', 
    'position'=>'Engineer', 
    'closing' =>'Kind regards'
];

Our output would be:

Hello, my name is Adam and I am applying for the position of engineer. Kind regards, Adam

You can see this in action in example 5.