在 TWIG 中使用 PHP 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8180585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:06:55  来源:igfitidea点击:

Use PHP function in TWIG?

phpsymfonytwig

提问by Martin Sowning

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?

我如何实现这一目标?

采纳答案by Wesley van Opdorp

What you need are functionsor filters. You can easily add these using the examples.

您需要的是函数过滤器。您可以使用示例轻松添加这些。

回答by Alexandr Karbivnichiy

// $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. All other function related classes in Twig are deprecated since 1.12 (to be removed in 2.0).

Twig_SimpleFunction 是首选使用的类。从 1.12 开始不推荐使用 Twig 中所有其他与函数相关的类(将在 2.0 中删除)。

In a Symfony2 controller:

在 Symfony2 控制器中:

$twig = $this->get('twig');

回答by umpirsky

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.

请参阅官方扩展存储库

回答by Nenai

If you're working in symfony 2 this should also help. Concept is the same but you put the code somewhere else and format it a little differently.

如果您在 symfony 2 中工作,这也应该有所帮助。概念是相同的,但您将代码放在其他地方并对其进行稍微不同的格式化。

http://symfony.com/doc/2.0/cookbook/templating/twig_extension.html

http://symfony.com/doc/2.0/cookbook/templating/twig_extension.html