Skip to content

Instantly share code, notes, and snippets.

@kstefan
Last active December 15, 2015 14:18
Show Gist options
  • Select an option

  • Save kstefan/5273186 to your computer and use it in GitHub Desktop.

Select an option

Save kstefan/5273186 to your computer and use it in GitHub Desktop.
Example of using macros in Twig
{% macro valueOrDefault(value, default, attribute) %}
{% if value %}
{{ attribute ? attribute(value, attribute) : value }}
{% else %}
{{ default }}
{% endif %}
{% endmacro %}
{% macro optionalValue(value, attribute) %}
{% import _self as self %}
{% set default %}
<span class="empty">empty</span>
{% endset %}
{{ self.valueOrDefault(value, default, attribute) }}
{% endmacro %}
{% macro requiredValue(value, attribute) %}
{% import _self as self %}
{% set default %}
<span class="label label-important">required</span>
{% endset %}
{{ self.valueOrDefault(value, default, attribute) }}
{% endmacro %}
<!--
class Team {
public name;
}
class User {
public email;
public phone;
/** @var Team|null */
public team;
}
$user = new User();
$user->phone = '721123456';
-->
<table>
<tr>
<th>E-mail</th>
<td>
<span class="label label-important">required</span>
</td>
</tr>
<tr>
<th>Phone</th>
<td>721123456</td>
</tr>
<tr>
<th>Team</th>
<td>
<span class="empty">empty</span>
</td>
</tr>
</table>
{% import "common.twig" as common %}
<table>
<tr>
<th>E-mail</th>
<td>{{ common.requiredValue(user.email) }}</td>
</tr>
<tr>
<th>Phone</th>
<td>{{ common.optionalValue(user.phone) }}</td>
</tr>
<tr>
<th>Team</th>
<td>
{{ common.optionalValue(user.team, 'name') }}
</td>
</tr>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment