Last active
December 15, 2015 14:18
-
-
Save kstefan/5273186 to your computer and use it in GitHub Desktop.
Example of using macros in Twig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {% 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 %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!-- | |
| 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {% 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