Yoan Arnaudov
Yoan Arnaudov

Reputation: 4134

PHP twig conditional filter

Let's say I have something like this:

<img src='{{ asset(article.image.path) | imagine_filter('watermarked') }}' />

what I want to do is apply imagine_filter('watermarked') only if article.isWatermarked() equals to true.

Is there any slicke way of doing this? Or I'm stuck with

{% set src = asset(article.image.path) %}
{% if article.isWatermarked() %}
{% set src = asset(article.image.path) | imagine_filter('watermarked') %}
{% endif %}
<img src='{{ src }}' />

Upvotes: 2

Views: 1637

Answers (2)

Kep
Kep

Reputation: 5857

Depending on how many places you need that functionality in you could put it in a macro:

macros.twig:

{%- macro wmImage(article) -%}
    {%- set src = article.watermarked ? asset(article.image.path) | imagine_filter('watermarked') : asset(article.image.path) -%}
    <img src="{{ src }}"/>
{%- endmacro -%}

In your template(s):

{%- import 'macros.twig' as 'macros' -%}

Usage:
{{ macros.wmImage(article) }}

Upvotes: 2

user1915746
user1915746

Reputation: 587

This should work

<img src='{{ article.isWatermarked() ? asset(article.image.path) | imagine_filter('watermarked') : asset(article.image.path) }}' />

See ternary operator in doc: https://twig.sensiolabs.org/doc/2.x/templates.html#other-operators

Upvotes: 3

Related Questions