Jamon Tutorial - 4. Escaping Text
Templates usually construct text in a structured language such as HTML or XML, or even URLs. Each of these languages has restrictions on allowed characters or sequence of characters. Escaping modifies a string to adhere to the rules of the particular language in which the string will be expressed.Rules for escaping text
- Static content In general, any characters appearing in a template are output literally, whitespace included. One notable exception is that if a newline is preceded by a backslash, then neither the newline nor the backslash are output.
- Emit statements
The value of a java expression can be emitted by enclosing the
expression in
<%...%>pairs, e.g.<% person.getFirstName().substring(0,10) %>
Note that there must be at least one whitespace character following the<%.Before a Java expression is emitted, the string that represents it is escaped. The usual default escaping mechanism is HTML, so for example the following template
this <% "&" %> that
producesthis & that
However different escaping mechanisms can be specified in the template itself. A string can be emitted with no escaping as follows:this <% "&" #n %> that
producingthis & that
The available escaping mechanism are-
HTML (use
#hin the emit block) -- produces output suitable for inclusion in the body of HTML elements -
Strict HTML (use
#Hin the emit block) -- produces output suitable for use as an HTML attribute value (it is similar to HTML escaping but also escapes quotes and apostrophes) - XML (use
#xin the emit block) - URL (use
#uin the emit block) - None (use
#nin the emit block)
-
HTML (use
- Setting the default escaping mechanism
The default escaping rule for a template is HTML. This default
can be changed for a particular template by using the
directive
<%escape #?>.
Example
Suppose the templateEscapingTemplateA.jamon contains
<%args>
String name = "Somebody";
String greeting;
</%args>
<html>
<body>
<% greeting %> <% name %> <br />
</body>
</html>
If this template is called by the java code
EscapingTut4a.java:
import java.io.OutputStreamWriter;
public class EscapingTut4a {
public static void main(String[] argv) throws Exception {
new EscapingTemplateA()
.setName("Duke & Co.")
.render(new OutputStreamWriter(System.out), "Hello");
}
}
Then the output of the template's render method will be
<html>
<body>
Hello Duke & Co. <br />
</body>
</html>
In contrast, if the template
EscapingTemplateB.jamon containing
<%escape #n>
<%args>
String name = "Somebody";
String greeting;
</%args>
<html>
<body>
<% greeting %> <% name %> <br />
</body>
</html>
is called by the java code
EscapingTut4b.java:
import java.io.OutputStreamWriter;
public class EscapingTut4b {
public static void main(String[] argv) throws Exception {
new EscapingTemplateB()
.setName("Duke & Co.")
.render(new OutputStreamWriter(System.out), "Hello");
}
}
Then the output of the template's render method will be
<html>
<body>
Hello Duke & Co. <br />
</body>
</html>