1

I'm looking for a solution on the best way to setup a macro for buttons that are defined in a matrix fieldtype.

My current code works fine but it really isn't that DRY and I feel it could be made better.

I first import my button macro in a main template:

{% import "_includes/buttons" as buttons %}

Then my code for the matrix field is:

{% for block in cube.button %}
   {{ buttons.span(block.buttonType, block.buttonText, block.buttonColour, block.buttonSize, block.fullWidthButton, cube.linkUrl) }}
{% endfor %}

And now my not so DRY button macro

{% macro span(type, text, colour, size, fullWidth, url) -%}
    <span class="btn {{ type }} {{ colour }} {{ size }}{% if fullWidth %} btn-block{% endif %}">{{ text }}</span>
{% endmacro -%}

{% macro a(type, text, colour, size, fullWidth, url) -%}
    <a href="{{ url }}" class="btn {{ type }} {{ colour }} {{ size }}{% if fullWidth %} btn-block{% endif %}">{{ text }}</a>
{% endmacro -%}

{% macro button(type, text, colour, size, fullWidth, url) -%}
    <button class="btn {{ type }} {{ colour }} {{ size }}{% if fullWidth %} btn-block{% endif %}">{{ text }}</button>
{% endmacro -%}

{% macro submit(type, text, colour, size, fullWidth, url) -%}
    <input type="submit" class="btn {{ type }} {{ colour }} {{ size }}{% if fullWidth %} btn-block{% endif %}" value="{{ text }}"/>
{% endmacro -%}
2

You could factor out that repeated class=... like so:

{% macro _btnClass(type, colour, size, fullWidth) %}
    class="btn {{ type }} {{ colour }} {{ size }}{% if fullWidth %} btn-block{% endif %}"
{% endmacro %}

{% macro span(type, text, colour, size, fullWidth, url) -%}
{% import _self as self %}
    <span {{ self._btnClass(type, colour, size, fullWidth) }}>{{ text }}</span>
{% endmacro -%}

It is not clear from your question how you decide which buttons macro to call. Perhaps that code needs to be made DRYer.

  • Updated question with the macro import: which is just one file that holds all the different macros. – since1976 Dec 29 '14 at 22:16
  • You must be calling buttons.a and buttons.button and buttons.submit somehow, but I'm not sure how. – Marion Newlevant Dec 30 '14 at 0:15
  • Ah you are absolutely right. Thought I would be able to set that as a var and use that. Turns out that doesn't work. :( – since1976 Dec 30 '14 at 0:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.