如何在TWIG中的宏中访问_context变量? [英] How do I access the _context variable within a macro in TWIG?

查看:55
本文介绍了如何在TWIG中的宏中访问_context变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在宏中访问我的树枝变量之一.我知道我不能直接做到这一点.

I'm trying to access one of my twig variables in a macro. I know I can't do this directly.

与PHP函数一样,宏无法访问当前模板变量

as with PHP functions, macros don't have access to the current template variables

但页面状态相同:

您可以使用特殊的_context变量将整个上下文作为参数传递.

You can pass the whole context as an argument by using the special _context variable.

将_context传递到宏并在宏中访问它的语法是什么?

What's the syntax for passing _context to the macro, and for accessing it within the macro?

谢谢

推荐答案

请考虑以下示例:

1)在当前上下文中创建一个变量

1) Create a variable in the current context

{% set x = 42 %}

2)声明一个将对象作为参数的宏

2) Declare a macro that takes an object as parameter

{% macro test(variables) %}
   variable x = {{ variables.x | default('undefined') }}
{% endmacro %}

3)使用特殊的_context对象调用您的宏

3) Call your macro, with the special _context object

{{ _self.test(_context) }}

这将显示:

变量x = 42

variable x = 42

这篇关于如何在TWIG中的宏中访问_context变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆