Reputation: 165
I have a twig template than generates a Latex file. It works fine except that it issues characters escaped for html.
So for instance, the DB returns the string Rosie & Jim
.
Twig makes that Rosie & Jim
.
For latex I need the &
to actually render as \&
.
Therefore I think I need a custom escaper for Latex as mentioned here: https://twig.sensiolabs.org/doc/2.x/filters/escape.html#custom-escapers
However, I'm a little green when it comes to twig and can't find any examples of actual escapers anywhere. Does anyone know:
a) Is this what I actually need?
b) What I actually need to do to make one?
Upvotes: 2
Views: 747
Reputation: 165
Right so I ended up setting it as a service and calling it from the controller as and when it's needed.
Not sure if it's best practice but it works for me.
The service:
<?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;
);
}
}
Then in app/config/services.yml:
services:
app.latex:
class: AppBundle\FunBundle\Service\Latex
arguments: ['@twig']
Then in a controller action:
$latexer = $this->get('app.latex');
$latexer->escaper();
And in the twig template itself:
{% autoescape 'latex' %}
# latex/twig goes here
{% end autoescape %}
Ended up writing it up here on my site, which includes a full example of a LaTeX escaper.
Upvotes: 1