Skip to content

Instantly share code, notes, and snippets.

@joelpittet
Last active August 29, 2015 13:57
Show Gist options
  • Save joelpittet/9772785 to your computer and use it in GitHub Desktop.
Save joelpittet/9772785 to your computer and use it in GitHub Desktop.
Example Twig Macro
{
"require": {
"twig/twig": "1.*"
}
}
<?php
require_once 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('.');
$twig_options = [
'cache' => FALSE,
'autoescape' => TRUE,
'strict_variables' => FALSE,
// 'debug' => TRUE,
'auto_reload' => TRUE,
];
$twig = new Twig_Environment($loader, $twig_options);
// $twig->addExtension(new Twig_Extension_Debug());
// The links.
$links = [
[
'name' => 'link 1',
'href' => '#',
],
[
'name' => 'link 2',
'href' => '#',
'links' => [
[
'name' => '<b>sub link 2.1</b>',
'href' => '#',
'links' => [],
],
[
'name' => 'sub link 2.2',
'href' => '#',
'links' => [],
],
],
],
];
echo $twig->render('page.twig', ['links' => $links]);
{% macro menu_links(links) %}
{% if links %}
<ul>
{% for link in links %}
<li>
<a href="{{ link.href }}">{{ link.name }}</a>
{% if link.links %}
{{ _self.menu_links(link.links) }}
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% endmacro %}
{% import "menu.twig" as menu %}
<!DOCTYPE html>
<html>
<body>
{{ menu.menu_links(links) }}
</body>
</html>
@joelpittet
Copy link
Author

Should be able to just download these and run composer update (if you have composer).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment