Mal ein praktisches Twig Beispiel anhand eines Newstemplates:
Atm haben wir 2 Templates für ein News Modul (eines davon kann man nicht pro Modul sondern nur pro Theme ändern). Das wird deshalb so gehandhabt, damit unterschiedlich ausführliche Listings nicht ein komplettes Template brauchen.
Mit Twig kann man das ähnlich handhaben, allerdings kann man hier jetzt auch alles pro Modul ändern und trotzdem nur eine Einstellung im Backend brauchen:
news.xhtml.twig
HTML-Code:
{% macro loopclasses(loop) %}
{%- if loop.index is even %}even{% endif -%}
{%- if loop.index is odd %} odd{% endif -%}
{%- if loop.first %} first{% endif -%}
{%- if loop.last %} last{% endif -%}
{% endmacro %}
{% block news %}
<div class="block mod_news">
{% block listing %}
{% for article in articles %}
{% block article %}
<div class="{{ _self.loopclasses(loop) }}" />
{% block headline %}<h1>{{ article.headline }}</h1>{% endblock headline %}
{% block date %}<p class="date">{{ article.date }}</p>{% endblock date %}
{% block text %}<p class="flow">{{ article.text }}</p>{% endblock text %}
</div>
{% endblock article %}
{% else %}
{% block empty %}<p>Zur Zeit keine Neuigkeiten</p>{% endblock empty %}
{% endfor %}
{% endblock listing %}
</div>
{% endblock news %}
Jetzt möchte man das ganze als Tabelle haben:
news_table.xhtml.twig
HTML-Code:
{% extends news.xhtml.twig %}
{% import news.xhtml.twig as generalmakros %} {# gets makros #}
{# wrapping table #}
{% block listing %}<table><thead> ... </thead><tbody>{{ parent() }}</tbody></table>{% endblock listing %}
{# wrapping table rows #}
{% block article %}<tr class="{{ generalmakros.loopclasses(loop) }}">{{ block('headline') }}{{ block('date') }}{{ block('text') }}</tr>{% endblock article %}
{# wrapping table cells #}
{% block headline %}<td>{{ parent() }}</td>{% endblock headline %}
{% block date %}<td>{{ parent() }}</td>{% endblock date %}
{% block text %}<td>{{ parent() }}</td>{% endblock text %}
{# wrapping empty #}
{% block empty %}<tr><td colspan="3">{{ parent() }}</td></tr>{% endblock empty %}
Von all dem Blockkram ist später nach dem Compiling nichts mehr zu sehen und es ist schnell!
Lesezeichen