You can make use Markup class
which defines an object that passes safe strings through the render system.
1.) You first need to create a TwigExtension.php class inside a module and define a function which will actually return a formatted string.
2.) Use that function inside any of your twig files to render formatted strings.
3.) Do Rebuild the cache, using Drush cr
.
-> Create a module_name.services.yml file under modules/module_name:
services:
module_name.twig.TwigExtension:
class: Drupal\module_name\TwigExtension
tags:
- {name: twig.extension}
-> Create a TwigExtension.php under modules/module_name/src/TwigExtension.php :
<?php
namespace Drupal\module_name;
use Drupal\Core\Render\Markup;
/**
* Class DefaultService.
*
* @package Drupal\module_name
*/
class TwigExtension extends \Twig_Extension {
/**
* {@inheritdoc}
* This function must return the name of the extension. It must be unique.
*/
public function getName() {
return 'block_display';
}
/**
* In this function we can declare the extension function
*/
public function getFunctions() {
return array(
new \Twig_SimpleFunction('render_string', array($this, 'render_string'), array('is_safe' => array('html'))),
);
}
/**
* Function to decode html special chars
*/
public function render_string($string) {
$render_string = Markup::create($string);
return $render_string;
}
-> **Insert twig function inside your twig file: **
{% set str = render_string('<a href="/this-is-new.html">This is new page</a>') %}
....
....
{{ str }}
Hope, this will help you.