Skip to content

Instantly share code, notes, and snippets.

@cursedcoder
Created August 25, 2012 14:21
Show Gist options
  • Save cursedcoder/3466385 to your computer and use it in GitHub Desktop.
Save cursedcoder/3466385 to your computer and use it in GitHub Desktop.
Twig Best Practice

Bad:

<div class="comment">
    <div class="message">some message</div>
    <div class="rate {% if comment.rate > 0%}green{% elseif comment.rate < 0 %}red{% else %}gray{% endif %}">{{ comment.rate }}</div>
</div>

Good:

{% set rateClass = comment.rate > 0 ? 'green' : comment.rate < 0 ? 'red' : 'gray' %}
<div class="comment">
    <div class="message">some message</div>
    <div class="rate {{ rateClass }}">{{ comment.rate }}</div>
</div>

Or:

{% if comment.rate > 0 %}
    {% set rateClass = 'green' %}
{% elseif comment.rate < 0 %}
    {% set rateClass = 'red' %}
{% else %}
    {% set rateClass = 'gray' %}
{% endif %}
<div class="comment">
    <div class="message">some message</div>
    <div class="rate {{ rateClass }}">{{ comment.rate }}</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment