Html.img in Twig template

Hello,

I wanted to know is there a way to use img function within HTML helper class in Twig?

This actually doesn’t work:

{{ html.img(‘update/index.png’, {‘alt’: ‘something’}) }}

I guess you need to mark output as |raw.

Unfortunately, that doesn’t do the trick. With, or without raw it does nothing (no output whatsoever, no error)

The above code is in index.twig view file. There is also a layout view main.twig, which has the following line:

{{ content | raw }}

Btw, should that line in the first post work? If yes, then maybe I have an error somewhere…

Yes, it should work. It may display no image though if it doesn’t point to valid image URL so check actual HTML.

1 Like

OK, found the solution. I am running PHP 8.0.1.
So the problem was in the configuration of the view component, globals directive:

    'view'         => [
        'class'     => yii\web\View::class,
        'renderers' => [
            'twig' => [
                'class'      => yii\twig\ViewRenderer::class,
                // set cachePath to false in order to disable template caching
                'cachePath'  => false, //'@runtime/Twig/cache',
                // Array of twig options:
                'options'    => YII_ENV
                    ? [
                        'debug'       => true,
                        'auto_reload' => true,
                    ]
                    : [],
                'extensions' => YII_DEBUG ? [
                    \Twig\Extension\DebugExtension::class,
                ] : [],
                // add Yii helpers or widgets here
                'globals'    => [
                    /*'html' => \yii\helpers\Html::class,*/       <-- THIS DOESN'T WORK
                    'html' => ['class' =>\yii\helpers\Html::class],    <-- THIS WORKS
                ],
                'uses'       => ['yii\bootstrap'],
            ],
        ],
    ],