树枝访问对象 [英] Twig access object

查看:21
本文介绍了树枝访问对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问树枝模板中对象的值.

i want to access the value of a object inside a twig template.

通常我会得到这样的回报:

Normally i would get the return like that:

echo $lang->get("test");

但是我如何在带有树枝的模板中做同样的事情?

But how can i do the same in the template with twig?

我尝试了很多方法,但没有一个奏效.

I tried so many methods but no one worked.

例如我试过:

{{ attribute(lang, get, 'test') }} 

结果

可捕获的致命错误:参数 3 传递给Twig_Node_Expression_GetAttr::__construct() 必须是Twig_Node_Expression_Array,Twig_Node_Expression_Constant 的实例给定

Catchable fatal error: Argument 3 passed to Twig_Node_Expression_GetAttr::__construct() must be an instance of Twig_Node_Expression_Array, instance of Twig_Node_Expression_Constant given

谢谢

推荐答案

您要做的是在 Twig 模板中使用参数调用对象上的方法.我不认为这是支持的,因为它可能被视为一个坏主意.不过,Twig 支持对象上的 getter 的概念,它们不带参数调用:

What you're trying to do is call a method on an object with parameters in a Twig template. I do not think this is supported, as it's probably viewed as a bad idea. Twig supports the notion of getters on an object though, which are called without parameters:

{{ lang.test }}

将尝试按以下顺序调用以下之一:

will try to invoke one of the following, in this order:

  • $lang->test
  • $lang->test()
  • $lang->getTest()
  • $lang->isTest()

如果对象实现了这些访问器和约定中的任何一个,Twig 会找到它.任何超出这个约定的东西,比如 get('test'),都不是 Twig 哲学的一部分.而且它通常不是一个广泛使用的习语,因此您可能应该坚持使用上述方法之一.

If the object implements any of these accessors and conventions, Twig will find it. Anything outside of this convention, like get('test'), is not part of the Twig philosophy. And it's not a widely used idiom in general, so you should probably stick to one of the above methods.

请参阅http://twig.sensiolabs.org/doc/templates.html#variables.

您可以实现 __isset__get__call 魔术方法来支持这些访问器方法之一.

You can implement __isset, __get or __call magic methods to support one of these accessor methods.

这篇关于树枝访问对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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