Php 如何在Twig中对HTML转义文本进行URL编码?
我有一个字符串Php 如何在Twig中对HTML转义文本进行URL编码?,php,symfony,twig,Php,Symfony,Twig,我有一个字符串Picture>1000个单词,它存储在Picture 1000个单词中。我需要对原始字符串进行URL编码才能获得图片%20%3E%201000%20个单词 我尝试了不同的过滤器序列,但没有一个能产生预期的结果 {# title = "Picture > 1000 words" #} {{ title | url_encode(true) }} {{ title | raw | url_encode(true) }} {{ title | url_encode(
Picture>1000个单词
,它存储在Picture 1000个单词
中。我需要对原始字符串进行URL编码才能获得图片%20%3E%201000%20个单词
我尝试了不同的过滤器序列,但没有一个能产生预期的结果
{# title = "Picture > 1000 words" #}
{{ title | url_encode(true) }}
{{ title | raw | url_encode(true) }}
{{ title | url_encode(true) | raw }}
所有3种情况下的结果都是相同的:
Picture%20%26gt%3B%201000%20words
。如何避免细枝对已经转义的文本进行编码并获得所需的结果?要获得此图片%20%3E%201000%20words
您应该拥有没有html实体的原始字符串
因此,这应该是可行的:
{% set title = "Picture > 1000 words" %}
{{ title | url_encode(true) }}
如果您确实需要解码模板内的实体,则可以为此注册自定义筛选器:
$filter = new Twig_SimpleFilter('decode_entities', function ($string) {
return html_entity_decode($string);
});
// then connect it with environment
$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
然后像这样使用它:
{{ title | decode_entities | url_encode(true) }}
编辑
刚刚使用最新的上游细枝尝试了您的示例,这正如您所期望的:
{{ title | raw | url_encode(true) }}
您的问题是字符串实体不正确
是html_实体的必需结尾,因此它应该是
@Baldrs tx。键入错误。谢谢!你的定制过滤器建议对我有用。将尝试更新Twig以查看raw
是否也有效。