如何使用 Twig 函数返回和插入 HTML 代码?

2022-01-22 00:00:00 html twig twig-extension

我正在尝试使用 Twig 动态添加一些图像.所以我定义了一个名为 setImgService 的新 Twig 函数,它基本上检查服务名称,并根据它,根据它的图像返回一些 HTML 代码.

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.

功能代码:

$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 代码.

It returns HTML code like plain text.

有什么帮助吗?

推荐答案

Twig 默认转义输出.要在函数的 twig 中显示 HTML,您可以使用过滤器 raw 或返回 Twig_Markup,它标记输出是安全的,因此不会被转义.

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.

原始过滤器

{{ 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');  
    }
});

相关文章