Php 为细枝制作定制乳胶逃逸器
我有一个生成Latex文件的细枝模板。它工作得很好,只是发出了为html转义的字符 例如,DB返回字符串Php 为细枝制作定制乳胶逃逸器,php,symfony,twig,Php,Symfony,Twig,我有一个生成Latex文件的细枝模板。它工作得很好,只是发出了为html转义的字符 例如,DB返回字符串Rosie&Jim Twig制作的Rosie&;吉姆 对于latex,我需要&实际渲染为\& 因此,我想我需要一个定制的乳胶逃逸器,如下所述: 然而,我对细枝有点生疏,在任何地方都找不到任何真正逃脱者的例子。有谁知道: a) 这是我真正需要的吗 b) 我实际上需要做什么才能做一个呢?对,所以我最终将它设置为一个服务,并在需要时从控制器调用它 不确定这是否是最佳实践,但它对我有效 服务:
Rosie&Jim
Twig制作的<代码>Rosie&;吉姆
对于latex,我需要&
实际渲染为\&
因此,我想我需要一个定制的乳胶逃逸器,如下所述:
然而,我对细枝有点生疏,在任何地方都找不到任何真正逃脱者的例子。有谁知道:
a) 这是我真正需要的吗
b) 我实际上需要做什么才能做一个呢?对,所以我最终将它设置为一个服务,并在需要时从控制器调用它 不确定这是否是最佳实践,但它对我有效 服务:
<?php
namespace AppBundle\FunBundle\Service;
class Latex
{
public function __construct($twig)
{
$this->twig = $twig;
}
public function escaper()
{
// Get twig env
$twig = $this->twig;
// Start setEscaper called 'latex' - call it what you want
$twig->getExtension('Twig_Extension_Core')->setEscaper('latex',
function($twig, $string, $charset){
// Replace every instance of '&' with '\&'
$string = str_replace("&", "\\&", $string);
}
return $string;
);
}
}
然后在控制器操作中:
$latexer = $this->get('app.latex');
$latexer->escaper();
在细枝模板本身中:
{% autoescape 'latex' %}
# latex/twig goes here
{% end autoescape %}
最后写在我的网站上,其中包括一个乳胶逃逸器的完整示例。您可能希望,
LaTeX
作为细枝模板变量。@JaredFarrish,它只输出原始数据。我仍然需要逃脱,只是不同而已。
{% autoescape 'latex' %}
# latex/twig goes here
{% end autoescape %}