betandr
betandr

Reputation: 13

Conditional HTML block with Twig

I'm using Silex and Twig for an app and I'd like to use Twig to hide or display content based on a method call. I'd like a custom tag like:

{{ 'foo'|check }}
    <p>This will only be displayed if check passes</p>
{{ endcheck }}

...then a method elsewhere such as:

check($key) {
    if($key === 'foo') {
        ...
    } else {
        ....
    }
}

...which would decide if the HTML content is displayed.

Upvotes: 0

Views: 949

Answers (2)

Zombiesplat
Zombiesplat

Reputation: 953

You're missing the point of TWIG. One of the primary reasons TWIG exists is to keep PHP out of the templates. So if you have something very complicated then process the array before you pass it to TWIG otherwise if it's simple like you've described then just have the twig emulate that functionality.

{% if row.val == 'foo' %}
    this will be displayed
{% else %}
    maybe you do not want anything displayed?
{% endif %}

Upvotes: 0

sjagr
sjagr

Reputation: 16512

As far as I know, you would have your method programmed as:

check($key) {
    if($key === 'foo') {
        return true;
    } else {
        return false;
    }
}

And then your custom filter would be used like this:

{% if 'foo'|check %}
    <p>This will only be displayed if check passes</p>
{% endif %}

You would only use {{ }} for straight output (similar to <?= ?> in PHP.)

Upvotes: 1

Related Questions