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

1

3

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?

Ottilie answered 13/6, 2016 at 19:36 Comment(0)
H
4

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

WARNING

When using Twig v3 you need to use new \Twig\Markup(...) instead of new Twig_Markup(...)

Hanafee answered 14/6, 2016 at 5:56 Comment(1)
It seems to be safer returning a Twig_Markup. I'm gonna try it.Ottilie

© 2022 - 2024 — McMap. All rights reserved.