Jun 2, 2014

Twig template with "if" conditional

The next step I took was to implement the use of a D7 template file that contains conditional markup wrapped by PHP, converting it to Twig. The original code looked something like the following. I have removed most of the markup, keeping just enough to illustrate the point.
<p>The basic configuration and design ... </p>

<?php if (($variables['form']['optimizely_project_code']['#default_value'] == 0) && ($variables['form']['optimizely_oid']['#value'] == 1)): ?>

  <p>In order to use this module, ... </p> 
  <p>The default Project ...  </p>


<?php endif; ?>

<?php echo drupal_render_children($form)

Here's a version for Twig.
<p>The basic configuration and design ... </p>

{% if form['optimizely_project_code']['#default_value'] == 0 and form['optimizely_oid']['#value'] == 1 %}

  <p>In order to use this module, ... </p> 
  <p>The default Project ...  </p>


{% endif %}

{{ form }}

As in the previous post, {{  }} is used to print the expression that is enclosed, which may be a variable name, a string literal, etc.

There is an alternate syntax for array expressions that is more compact and a little easier to read. The following two lines are equivalent.
form['optimizely_oid']['#value']
form.optimizely_oid['#value'] 
But the next line results in a syntax error because of the pound sign # so you can't always use this dot notation.
form.optimizely_oid.#value

Note:  <?php  ?>  delimiters and their enclosed PHP code are ignored in Twig templates.

Sources:

TWIG > tags > if
http://twig.sensiolabs.org/doc/tags/if.html

Creating and Using Templates
http://symfony.com/doc/current/book/templating.html

No comments:

Post a Comment