问题
I'm trying to add some images dynamically with Twig. So I defined a new Twig function called setImgService
which basically chechs for a service name and depending on it, it will return some HTML code according to its image.
Function code:
$setImgService = new Twig_SimpleFunction('setImgService', function($serviceName){
switch ($serviceName){
case "Analitycs":
return '<img src="assets/img/analitycs.png">';
case "Hosting":
return '<img src="assets/img/hosting.png">';
case "SEO":
return '<img src="assets/img/seo.png">';
case "Maintenance":
return '<img src="assets/img/maintenance.png">';
case "Your own domain":
return '<img src="assets/img/domain.png">';
case "BackUp":
return '<img src="assets/img/backup.png">';
}
});
// Add function to Twig
$twig->addFunction($setImgService);
But when I use
{{ setImgService('serviceName') }}
It returns HTML code like plain text.
Any help, please?
回答1:
Twig
escapes output by default. To display HTML
inside twig
from a function you can either use the filter raw
or return a Twig_Markup
, which marks the output as safe so it won't be escaped.
raw filter
{{ setImgService('serviceName') | raw }}
Twig_Markup
$setImgService = new Twig_SimpleFunction('setImgService', function($serviceName){
switch ($serviceName){
case "Analitycs":
return new Twig_Markup('<img src="assets/img/analitycs.png">', 'UTF-8');
case "Hosting":
return new Twig_Markup('<img src="assets/img/hosting.png">', 'UTF-8');
case "SEO":
return new Twig_Markup('<img src="assets/img/seo.png">', 'UTF-8');
case "Maintenance":
return new Twig_Markup('<img src="assets/img/maintenance.png">', 'UTF-8');
case "Your own domain":
return new Twig_Markup('<img src="assets/img/domain.png">', 'UTF-8');
case "BackUp":
return new Twig_Markup('<img src="assets/img/backup.png">', 'UTF-8');
}
});
来源:https://stackoverflow.com/questions/37797832/how-to-return-and-insert-html-code-with-a-twig-function