Kevin Burke
Kevin Burke

Reputation: 64774

Mix unsanitized data, HTML in a mustache template variable

I'm trying to pass a message through to a Mustache template that looks something like this:

The url you provided, http://example.com, is not valid.

The user specifies the URL, so the URL needs to be escaped. However I want to put <code> tags around the URL, so it stands out from the surrounding text, so the code tags need to be passed through without being escaped.

I could write something like this:

{{text_before_url}}<code>{{url}}</code>{{text_after_url}} 

However, the text of the message varies and it's not always going to fit that structure.

I could also try outputting the raw text with three braces, {{{messages}}}, and escaping the URL with something like htmlentities($url), but if someone adapts the program later to pass in a new message, and passes in data without realizing it has to be escaped, then we are in big XSS trouble.

I might just be out of luck, and I understand the value of having a simple templating engine, but is there some way I can tell Mustache that the HTML tags are OK, while escaping the rest of the output?

Kevin

Upvotes: 5

Views: 2527

Answers (1)

Ronan
Ronan

Reputation: 4321

Using {{variable}} inside a template for 5 > 2 will result in 5 &gt; 2, where as the usage of {{{variable}}} (3 mustaches) will result in 5 > 2.

Cf. documentation: https://github.com/defunkt/mustache#escaping

Upvotes: 6

Related Questions