如何在树枝中调用ucwords?

How to call ucwords in twig?

编辑:2016 年 12 月 3 日

我找到了几篇关于从 twig 调用 php 函数的帖子,表明应该支持它,但它似乎不起作用。

{{ ucwords( item|replace({'_':' '}) ) }}

结果:l

Slim Application Error

The application could not run because of the following error:

Details

Type: Twig_Error_Syntax Message: The function "ucwords" does not exist in "home.twig" at line 101

File: /usr/share/dev89/html/vhosts/local/libs/vendor/twig/twig/lib/Twig/ExpressionParser.php Line: 572

更新:Twig 2.x 带有 capitalize 过滤器,它正是这样做的。


并非所有 PHP 功能都在 Twig 中可用。只有 少数 Twig filters and functions 与 PHP.

中的同类名称同名

但是您可以轻松地为 ucwords 创建自己的 Twig extension – 过滤器和函数:

<?php

namespace Acme\TestBundle\Twig;

class UcWordsExtension extends \Twig_Extension
{
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('ucwords', 'ucwords')
        ];
    }

    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('ucwords', 'ucwords')
        ];
    }
    
    public function getName()
    {
        return 'ext.ucwords';
    }

}

Twig_SimpleFunction/Twig_SimpleFilter的第一个参数是function/filter在Twig中的名称。第二个参数是 PHP 可调用的。由于 ucfirst 函数已经存在,将其名称作为字符串传递就足够了。

在 Twig 中测试:

{{ "test foobar"|ucwords }} {# filter #} <br>
{{ ucwords("test foobar") }} {# function #} 

Returns:

Test Foobar
Test Foobar

正如@lxg 所说,不可能从 Twig 模板中调用所有 PHP 函数……除非您想这样做并定义自己的 filters/functions。对于 "force" 您创建不包含太多逻辑的良好模板来说,这不是缺点,而是一件好事。

无论如何,在这种特殊情况下,Twig 已经包含一个名为 title 的过滤器,它应用 "title case",相当于 ucwords() PHP 函数:

{{ item|replace({'_':' '})|title }}

您可以使用大写 twig 过滤器:

{{ item | capitalize }}

为什么不使用 title 过滤器? 我一直在寻找一个可以像 ucwords() php 函数一样工作的过滤器,我在 Twig Documentation 中找到了这个 title 过滤器。

使用示例;

{{ 'i am raziul islam'|title }}

Outputs: I Am Raziul Islam