我尝试使用Twig动态添加一些图片。所以我定义了一个名为setImgService
的新Twig函数,该函数基本上为服务名称填充,根据它,它将根据其图像返回一些HTML代码。
功能代码:
$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);
但是当我使用
时{{ setImgService('serviceName') }}
它返回纯文本等HTML代码。
请帮忙吗?
答案 0 :(得分:1)
Twig
默认转义输出。要在函数中显示HTML
twig
,您可以使用过滤器raw
或返回Twig_Markup
,这会将输出标记为安全,因此不会对其进行转义。
原始过滤器
{{ 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');
}
});