How can I HTML escape in Erazor?

182 views Asked by At

I'm new to Haxe, and I'm trying to experiment with Ufront.

I got a problem using Erazor templates: I don't understand how to escape HTML when outputting variables.

With this simple template:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Users list</title>
</head>
<body>
    <ul>
        @for(user in users)
        {
            <li>@user.name</li>
        }
    </ul>
</body>

</html>

If any of the users has name '<script>', then the template will simply output <script> for its name.

How can I properly HTML escape in Erazor?

2

There are 2 answers

0
Franco Ponticelli On BEST ANSWER

Ufron automatically includes the helper class that contains the desired method:

<li>@Html.encode(user.name)</li>
0
Andrea Parodi On

How to HTML escape view arguments

In order to HTML escape an argument in your Erazor views, you could simply use the HTML helper method encode().

Supposing your argument is called pageContent and its value is:

<script>
    alert("BAD things could happens if you don't properly escape!!");
</script>

You can escape it using following code:

@Html.encode(pageContent)

Your template will be safely rendered as

&lt;script&gt;
    alert("BAD things could happens if you don't properly escape!!");
&lt;/script&gt;

Html.encode() internally uses StringTools.htmlEscape() in order to escape its argument.

Thanks to the kindly help of Franco, I've written a page on the Ufront site to explain how to HTML escape in Ufront.