How to return and insert HTML code with a Twig function?

▼魔方 西西 提交于 2019-12-10 10:47:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!