我有一个字符串Picture > 1000 words,它存储为 HTML 转义的Picture > 1000 words。我需要对原始字符串进行 URL 编码才能得到Picture%20%3E%201000%20words
我尝试了不同的过滤器序列,但没有一个产生所需的结果。
{# title = "Picture > 1000 words" #}
{{ title | url_encode(true) }}
{{ title | raw | url_encode(true) }}
{{ title | url_encode(true) | raw }}
Run Code Online (Sandbox Code Playgroud)
所有 3 种情况的结果都是相同的:Picture%20%26gt%3B%201000%20words。如何避免 Twig 对已经转义的文本进行编码并获得所需的结果?
为了得到这个Picture%20%3E%201000%20words你应该有没有 html 实体的原始字符串
所以这应该有效:
{% set title = "Picture > 1000 words" %}
{{ title | url_encode(true) }}
Run Code Online (Sandbox Code Playgroud)
如果您确实需要解码模板内的实体,您可以为此目的注册一个自定义过滤器:
$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);
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
{{ title | decode_entities | url_encode(true) }}
Run Code Online (Sandbox Code Playgroud)
编辑
刚刚用最新的上游树枝尝试了您的示例,这正如您所期望的那样:
{{ title | raw | url_encode(true) }}
Run Code Online (Sandbox Code Playgroud)
您的问题是字符串实体不正确
| 归档时间: |
|
| 查看次数: |
12594 次 |
| 最近记录: |