所以我对 Symfony2 还很陌生,我正在尝试在 twig 模板中使用
camelize
过滤器。但是,当我请求该页面时,我收到一条错误消息,指出过滤器不存在:
::base.html.twig 中不存在过滤器“camelize”
这是我的模板文件中的行:
{{ '你好世界' |骆驼化}}
过滤器列在 Twig 的快速参考页面上。
我很困惑,Symfony2 不支持所有 twig 的过滤器吗?好像少了很多,为什么呢?如果它不支持它们,那么有什么方法可以添加缺失的吗?
提前致谢!
edit 好吧,事实证明我是弱智,我需要记住检查我是否确实拥有正确的 git 项目。难怪我很困惑。谢谢回复!
Symfony 2 有用于驼峰式大小写的标题过滤器
{{ entity.yourstring | title }}
驼峰式书写你的字符串
您的链接指向 GitHub 上的 fork,这意味着原始项目的修改副本。原始项目是https://github.com/fabpot/Twig.
Twig 中没有
camelize
过滤器。内置过滤器位于此处。您可以按照本教程编写自己的 camilize 过滤器(实际上很简单......):如何编写自定义 Twig 扩展。
编辑:只是为了好玩,你可以写这样的东西:
class MyTwigExtension extends Twig_Extension
{
public function getFilters()
{
return array(
'camelize' => new Twig_Filter_Method($this, 'camelizeFilter'),
);
}
public function camelizeFilter($value)
{
if(!is_string($value)) {
return $value;
}
$chunks = explode(' ', $value);
$ucfirsted = array_map(function($s) { return ucfirst($s); }, $chunks);
return implode('', $ucfirsted);
}
public function getName()
{
return 'my_twig_extension';
}
}
请注意,这是一个快速且肮脏的过滤器!查看内置过滤器以学习最佳实践!
您要查找的过滤器名为“title”:http://twig.sensiolabs.org/doc/filters/title.html
这是 Craft CMS 3 中默认的最佳解决方案
Craft 3 现在有一个
|camel
树枝过滤器
https://docs.craftcms.com/v3/dev/filters.html#camel
{{ 'foo bar'|camel }}
{# Output: fooBar #}
如果有人不想为解决方案编写 php 函数或过滤器(如果您在编程过程中尝试在很多地方使用camelizer,建议您这样做),这里是一个仅使用 Twig 的解决方案删减单词并更新它们:
在这种情况下,我会将蛇箱变成骆驼箱,这有望覆盖所有可能的场景:
{% set snakeVariable = "snake_to_camel_case" %}
{# first we remove all the underscores _ from snakeVariable #}
{% set variable = tabName|replace({'_': ' '}) %} {# output : "snake to camel case" #}
{% set words = variable|split(' ') %}
{# output :
array:3 [▼
0 => "snake"
1 => "to"
2 => "camel"
3 => "case"
] #}
{# now we take the first word seperately #}
{% set firstWord = words|first %} {# output : snake }
{# here we take the rest of the words cutting out the first word with slice(1) #}
{# join the array words using join(' ') #}
{# uppercase every first letter of the words |title #}
{# remove whitespace between the words replace({' ': ''} #}
{% set restWords = words|slice(1)|join(' ')|title|replace({' ': ''}) %} {# output: ToCamelCase }
{# combine the whole variable back to one " snake ~ ToCamelCase #}
{% set allWords = firstWord ~ restWords %}
All words: {{ allWords }} {# output: snakeToCamelCase #}
我尝试使用代码内注释来解释过滤器和函数。