[英]Use PHP function in TWIG?
In PHP templates I can use php functions, for example: 在PHP模板中,我可以使用php函数,例如:
foreach ($users as $user){
echo someFunction($user->getName());
}
How can I make it in TWIG? 我怎样才能在TWIG中制作它?
{% for user in users %}
* {{ user.name }}
{% else %}
No user have been found.
{% endfor %}
How do I achieve this? 我该如何实现这一目标?
// $twig is a Twig_Environment instance.
$twig->registerUndefinedFunctionCallback(function($name) {
if (function_exists($name)) {
return new Twig_SimpleFunction($name, function() use($name) {
return call_user_func_array($name, func_get_args());
});
}
throw new \RuntimeException(sprintf('Function %s not found', $name));
});
In a twig template: 在树枝模板中:
{{ explode(",", "It's raining, cats and dogs.").0 | raw }}
this will output "It's raining". 这将输出“正在下雨”。 By default, returned values are escaped in Twig.
默认情况下,返回的值在Twig中进行转义。
Twig_SimpleFunction is the preferred class to use. Twig_SimpleFunction是首选使用的类。 All other function related classes in Twig are deprecated since 1.12 (to be removed in 2.0).
Twig中所有其他与函数相关的类从1.12开始被弃用(将在2.0中删除)。
In a Symfony2 controller: 在Symfony2控制器中:
$twig = $this->get('twig');
There is already a Twig extension that lets you call PHP functions form your Twig templates like: 已经有一个Twig扩展,允许您从Twig模板调用PHP函数,如:
Hi, I am unique: {{ uniqid() }}.
And {{ floor(7.7) }} is floor of 7.7.
See official extension repository . 查看官方扩展库 。
If you're working in symfony 2 this should also help. 如果你在symfony 2工作,这也应该有所帮助。 Concept is the same but you put the code somewhere else and format it a little differently.
概念是相同的,但您将代码放在其他地方并将其格式化有点不同。
http://symfony.com/doc/2.0/cookbook/templating/twig_extension.html http://symfony.com/doc/2.0/cookbook/templating/twig_extension.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.