renderWith() and html

Silverstripe Version:
4
Question:
So i’m having a small bit of trouble using the renderWith(show_message’) and outputting HTML into the template ‘show_message’.
My problem is that the message text doesn’t render the link in the text. It doesn’t seem to parse the <a href as html?
is there anything i did wrong here?

    $this->setMessage("Error", "Please go to the <a href=\"profile\"> profile page</a> before continuing");

    public function setMessage($type, $message)
    {
        $request = Controller::curr()->getRequest();
        $request->getSession()
            ->set('Message', array('MessageType' => $type, 'Message' => $message));
    }

    public function getMessage()
    {
        $session = $this->getRequest()->getSession();
        if ($message = $session->get('Message'))
        {
            $session->clear('Message');
            $messageData = new ArrayData($message);
            return $messageData->renderWith('Layout/show_message');
        }
    }

template…

<% if Message %>
	<p class='message' id='{$MessageType}Message'>
		$Message
	</p>
<% end_if %>

Thanks
Grant

Hi Grant, when you pass plain text to the template processor it will assume it’s just that - plain text - and will escape it appropriately to be displayed as readable text, replacing any characters that would be interpreted as html with entities. If you want that text to be treated as HTML you can either inform the template processor that it is HTML on the way in (by casting it as a HTMLFragment object), or you can tell the processor not to escape the text.

There are a few ways to cast your message as HTML. You could put this in your class to have the casting done for you by the template processor:

private static $casting = [
    'Message' => 'HTMLFragment'
];

or you could manually create a HTMLFragment object and pass it instead of a plain string:

$message = DBField::create(HTMLFragment::class, $message);

Or you could leave your php code how it is and skip the escaping in the template like this:

$Message.RAW

Hopefully one of those methods works for you :slight_smile:

More about all casting here: https://docs.silverstripe.org/en/4/developer_guides/templates/casting/

Hi JonoM,

I ended up using the $Message.raw
It seemed to work ok.

Thanks