Last active
February 23, 2017 20:21
-
-
Save kepek/677f9ad4a9ba7b3d7e1a98ef060657bc to your computer and use it in GitHub Desktop.
Twig Macros: Link
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/macros.html.twig' as macros %} | |
Advanced example: | |
{{ | |
macros.link('Blog', 'blog_index', { search: 'kepek' }, { | |
attributes: { | |
'data-component': 'myName', | |
'class': 'kepek' | |
} | |
}) | |
}} | |
<a href="//localhost/blog?search=kepek" class="route-link active kepek" data-component="myName"> | |
Blog | |
</a> | |
Simple example: | |
{{ macros.link('Contact', 'contact_public_form') }} | |
<a href="//localhost/contact" class="route-link"> | |
Contact | |
</a> | |
#} | |
{% macro link(label, name, parameters = [], options = {}) %} | |
{% | |
set defaults = { | |
schemeRelative: false, | |
activeClassName: 'active', | |
attributes: {} | |
} | |
%} | |
{% set options = defaults|merge(options) %} | |
{% set isActive = app.request.attributes.get('_route') starts with name %} | |
{% set url = url(name, parameters, options.schemeRelative)|default('#') %} | |
{% set classList = ['route-link'] %} | |
{% if isActive %} | |
{% set classList = classList|merge([options.activeClassName]) %} | |
{% endif %} | |
{% set attributes = defaults.attributes|merge(options.attributes) %} | |
{% if attributes.class is defined %} | |
{% set classList = classList|merge([attributes.class]) %} | |
{% endif %} | |
{% set attributes = attributes|merge({ class: classList|join(' ') }) %} | |
<a href="{{ url }}" {% for attrName, attrValue in attributes %}{{- attrName }}="{{ attrValue }}" {% endfor %}> | |
{{ label|default(url) }} | |
</a> | |
{% endmacro %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment