* 1.13.2 (2013-XX-XX)
+ * in the template can be directly called macros defined in the same template
* added support for named arguments for macros
* fixed fatal error that should be an exception when macro does not exist in template
.. versionadded:: 1.13.2
Support for macro call with named arguments was added in Twig 1.13.2.
+ Support for directly call macros defined in the same template was added in Twig 1.13.2.
Macros are comparable with functions in regular programming languages. They
are useful to reuse often used HTML fragments to not repeat yourself.
<p>{{ forms.input('username') }}</p>
+Macros defined in the same template can be directly called:
+
+.. code-block:: jinja
+
+ {% macro submit(name) %}
+ <input type="submit" value="{{ name }}" />
+ {% endmacro %}
+
+ <p>{{ submit('Send') }}</p>
+
+.. note::
+
+ If the macro name matches the name of a function, it need to be "imported"
+ via the :doc:`import<tags/import>`.
+
Alternatively, you can import individual macro names from a template into the
current namespace via the :doc:`from<tags/from>` tag and optionally alias them:
return new Twig_Node_Expression_MacroCall($alias['node'], $alias['name'], $this->createArrayFromArguments($args), $line);
}
- $class = $this->getFunctionNodeClass($name, $line);
+ try {
+ $class = $this->getFunctionNodeClass($name, $line);
+ } catch (Twig_Error_Syntax $e) {
+ if (!$this->parser->hasMacro($name)) {
+ throw $e;
+ }
+
+ return new Twig_Node_Expression_MacroCall(new Twig_Node_Expression_Name('_self', $line), $name, $this->createArrayFromArguments($args), $line);
+ }
return new $class($name, $args, $line);
}
--- /dev/null
+--TEST--
+Auto importing macros in the same file
+--TEMPLATE--
+{% macro test(a) %}
+{{ a }}
+{%- endmacro %}
+
+{% macro foo(a) %}
+foo: {{ test(a) }}
+{%- endmacro %}
+
+{{ test('foo') }}
+{{ foo('foo') }}
+{{ test(a = 'bar') }}
+--DATA--
+return array();
+--EXPECT--
+foo
+foo: foo
+bar