Twig: Add possibility to set default values for macro args

Created on 21 Sep 2011  路  6Comments  路  Source: twigphp/Twig

Take this macro definition for example: {% macro teaser(show, class, truncate) %}. By reading it, you have no idea which args are needed and which aren't. Twig also can't throw errors for missing arguments, so it's easy to make a mess.

If we could say: {% macro teaser(show, class, truncate = false) %}, the behavior of the code would be the same, but it's much more self-documenting, and if class is missing, Twig can now know that it's supposed to be there, and throw an exception. That'd be a BC break, but it could be done only when strict_variables is enabled.

Most helpful comment

+1
Workarround would be setting the default values at the beginning

{% macro input(name, value, type) %}
    {% set type = type|default('text') %}
{% endmacro %}

All 6 comments

Note that the problem gets much worse when you have 10 args, 5 of which are optional, and 30-50 lines of markup in the macro. At that point it's barely possible to define which are mandatory params, without spending 10 minutes analyzing the code.

Also need this feature.

+1

+1

This is particularly an issue, because there's no way to differentiate between a missing argument and an argument that was included, but is null. For example, if you have a macro defined like

{% macro(arg1,arg2) %}

There is no way to differentiate between {{ myMacro(goodArg,nullArg) }} and {{ myMacro(goodArg) }} from within the macro itself. arg2 resolves to null in both cases.

+1

+1
Workarround would be setting the default values at the beginning

{% macro input(name, value, type) %}
    {% set type = type|default('text') %}
{% endmacro %}
Was this page helpful?
0 / 5 - 0 ratings