You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@freemarker.apache.org by dd...@apache.org on 2017/03/13 10:58:23 UTC
[47/50] incubator-freemarker-site git commit: 2.3.26-nightly docs
preview
http://git-wip-us.apache.org/repos/asf/incubator-freemarker-site/blob/52c070a9/builds/2.3.26-nightly/app_faq.html
----------------------------------------------------------------------
diff --git a/builds/2.3.26-nightly/app_faq.html b/builds/2.3.26-nightly/app_faq.html
new file mode 100644
index 0000000..fda425b
--- /dev/null
+++ b/builds/2.3.26-nightly/app_faq.html
@@ -0,0 +1,1797 @@
+<!doctype html>
+<!-- Generated by FreeMarker/Docgen from DocBook -->
+<html lang="en" class="page-type-appendix">
+<head prefix="og: http://ogp.me/ns#">
+<meta charset="utf-8">
+<title>FAQ - Apache FreeMarker Manual</title>
+<meta http-equiv="X-UA-Compatible" content="IE=edge">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<meta name="format-detection" content="telephone=no">
+<meta property="og:site_name" content="Apache FreeMarker Manual">
+<meta property="og:title" content="FAQ">
+<meta property="og:locale" content="en_US">
+<meta property="og:url" content="http://freemarker.org/docs/app_faq.html">
+<link rel="canonical" href="http://freemarker.org/docs/app_faq.html">
+<link rel="icon" href="favicon.png" type="image/png">
+<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Roboto:500,700,400,300|Droid+Sans+Mono">
+<link rel="stylesheet" type="text/css" href="docgen-resources/docgen.min.css?1489402528979">
+<script>
+(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
+(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
+m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
+})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
+ga('create', 'UA-55420501-1', 'auto');
+ga('send', 'pageview');
+</script>
+</head>
+<body itemscope itemtype="https://schema.org/Code">
+ <meta itemprop="url" content="http://freemarker.org/docs/">
+ <meta itemprop="name" content="Apache FreeMarker Manual">
+
+ <!--[if lte IE 9]>
+ <div style="background-color: #C00; color: #fff; padding: 12px 24px;">Please use a modern browser to view this website.</div>
+ <![endif]--><div class="header-top-bg"><div class="site-width header-top"><a class="logo" href="http://freemarker.org" role="banner"> <img itemprop="image" src="logo.png" alt="FreeMarker">
+</a><ul class="tabs"><li><a href="http://freemarker.org/">Home</a></li><li class="current"><a href="index.html">Manual</a></li><li><a class="external" href="api/index.html">Java API</a></li></ul><ul class="secondary-tabs"><li><a class="tab icon-heart" href="http://freemarker.org/contribute.html" title="Contribute"><span>Contribute</span></a></li><li><a class="tab icon-bug" href="https://issues.apache.org/jira/browse/FREEMARKER/" title="Report a Bug"><span>Report a Bug</span></a></li><li><a class="tab icon-download" href="http://freemarker.org/freemarkerdownload.html" title="Download"><span>Download</span></a></li></ul></div></div><div class="header-bottom-bg"><div class="site-width search-row"><a href="index.html" class="navigation-header">Manual</a><div class="navigation-header"></div><form method="get" class="search-form" action="search-results.html"><fieldset><legend class="sr-only">Search form</legend><label for="search-field" class="sr-only">Search query</label><input id="searc
h-field" name="q" type="search" class="search-input" placeholder="Search" spellcheck="false" autocorrect="off" autocomplete="off"><button type="submit" class="search-btn"><span class="sr-only">Search</span></button></fieldset></form></div><div class="site-width breadcrumb-row"><ul class="breadcrumb" itemscope itemtype="http://schema.org/BreadcrumbList"><li class="step-0" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><a class="label" itemprop="item" href="index.html"><span itemprop="name">Apache FreeMarker Manual</span></a></li><li class="step-1" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><a class="label" itemprop="item" href="app.html"><span itemprop="name">Appendixes</span></a></li><li class="step-2" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><a class="label" itemprop="item" href="app_faq.html"><span itemprop="name">FAQ</span></a></li></ul><div class="bookmarks" title="Bookmarks"><span clas
s="sr-only">Bookmarks:</span><ul class="bookmark-list"><li><a href="alphaidx.html">Alpha. index</a></li><li><a href="gloss.html">Glossary</a></li><li><a href="dgui_template_exp.html#exp_cheatsheet">Expressions</a></li><li><a href="ref_builtins_alphaidx.html">?builtins</a></li><li><a href="ref_directive_alphaidx.html">#directives</a></li><li><a href="ref_specvar.html">.spec_vars</a></li><li>FAQ</li></ul></div></div></div> <div class="main-content site-width">
+ <div class="content-wrapper">
+ <div id="table-of-contents-wrapper" class="col-left">
+ <script>var breadcrumb = ["Apache FreeMarker Manual","Appendixes","FAQ"];</script>
+ <script src="toc.js?1489402528979"></script>
+ <script src="docgen-resources/main.min.js?1489402528979"></script>
+ </div>
+<div class="col-right"><div class="page-content"><div class="page-title"><div class="pagers top"><a class="paging-arrow previous" href="app.html"><span>Previous</span></a><a class="paging-arrow next" href="app_versions.html"><span>Next</span></a></div><div class="title-wrapper">
+<h1 class="content-header header-chapter" id="app_faq" itemprop="headline">FAQ</h1>
+</div></div> <div class="qandaset">
+
+ <ol>
+ <li>
+ <a href="#faq_jsp_vs_freemarker">
+
+ JSP versus FreeMarker?
+
+
+ </a>
+ </li>
+ <li>
+ <a href="#faq_picky_about_missing_vars">
+
+ Why is FreeMarker so picky about <code class="inline-code">null</code>-s
+ and missing variables, and what to do with it?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_number_grouping">
+
+ Why does FreeMarker print the numbers with strange
+ formatting (as 1,000,000 or 1�000�000 instead of 1000000)?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_number_decimal_point">
+
+ Why does FreeMarker print bad decimal and/or grouping
+ separator symbol (as 3.14 instead of 3,14)?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_number_boolean_formatting">
+
+ Why does FreeMarker give an error when I try to print a
+ boolean like <code class="inline-code">${aBoolean}</code>, and how to fix
+ it?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_template_not_found">
+
+ FreeMarker can't find my templates
+ (<code class="inline-code">TemplateNotFoundException</code> or
+ <code class="inline-code">FileNotFoundException</code>, "Template not
+ found" error message)
+ </a>
+ </li>
+ <li>
+ <a href="#faq_check_version">
+
+ The documentation writes about feature
+ <em>X</em>, but it seems that FreeMarker doesn't
+ know that, or it behaves in a different way as documented, or a
+ bug that was supposedly fixed is still present.
+ </a>
+ </li>
+ <li>
+ <a href="#faq_alternative_syntax">
+
+ The <code class="inline-code"><</code> and <code class="inline-code">></code> of
+ FreeMarker tags confuses my editor or the XML parser. What to
+ do?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_legal_variable_names">
+
+ What are the legal variable names?
+
+
+ </a>
+ </li>
+ <li>
+ <a href="#faq_strange_variable_name">
+
+ How can I use variable names (macro name, parameter name)
+ that contain minus sign (<code class="inline-code">-</code>), colon
+ (<code class="inline-code">:</code>), dot (<code class="inline-code">.</code>), or or other
+ special characters?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_jsp_custom_tag_syntax">
+
+ Why do I get "java.lang.IllegalArgumentException: argument
+ type mismatch" when I try to use <em>X</em> JSP
+ custom tag?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_servlet_include">
+
+ How to include other resources in a way as
+ <code class="inline-code">jsp:include</code> does it?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_parameter_unwrapping">
+
+ How can I get the parameters to my
+ plain-Java-method/<code class="inline-code">TemplateMethodModelEx</code>/<code class="inline-code">TemplateTransformModel</code>/<code class="inline-code">TemplateDirectiveModel</code>
+ implementation as plain
+ <code class="inline-code">java.lang.*</code>/<code class="inline-code">java.util.*</code>
+ objects?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_nonstring_keys">
+
+ Why I can't use non-string key in the
+ <code class="inline-code">myMap[myKey]</code> expression? And what to do
+ now?
+
+
+ </a>
+ </li>
+ <li>
+ <a href="#faq_simple_map">
+
+ When I list the contents of a map (a hash) with
+ <code class="inline-code">?keys</code>/<code class="inline-code">?values</code>, I get the
+ <code class="inline-code">java.util.Map</code> methods mixed with the real map
+ entries. Of course, I only want to get the map entries.
+ </a>
+ </li>
+ <li>
+ <a href="#faq_modify_seq_and_map">
+
+ How can I modify sequences (lists) and hashes (maps) in
+ FreeMarker templates?
+
+
+
+
+
+
+
+
+ </a>
+ </li>
+ <li>
+ <a href="#faq_null">
+
+ What about <code class="inline-code">null</code> and the FreeMarker
+ template language?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_capture">
+
+ How can I use the output of a directive (macro) in
+ expressions (as a parameter to another directive)?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_questionmark">
+
+ Why do I have "?"-s in the output instead of
+ character <em>X</em>?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_retrieve_calculated_values">
+
+ How to retrieve values calculated in templates after
+ template execution done?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_assign_to_dynamic_variable_name">
+
+ How to assign to (or <code class="inline-code">#import</code> into) a
+ dynamically constructed variable name (like to name that's stored
+ in another variable)?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_template_uploading_security">
+
+
+
+ Can I allow users to upload templates and what are the
+ security implications?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_implement_function_or_macro_in_java">
+
+ How to implement a function or macro in Java Language
+ instead of in the template language?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_nice_error_page">
+
+ In my Servlet
+ based application, how do I show a nice error page instead of a
+ stack trace when error occurs during template processing?
+ </a>
+ </li>
+ <li>
+ <a href="#faq_html_editor_mangles">
+
+ I'm using a visual HTML editor that mangles template tags.
+ Will you change the template language syntax to accommodate my
+ editor?
+ </a>
+ </li>
+ </ol>
+ <dl>
+
+
+
+ <dt class="question" id="faq_jsp_vs_freemarker">
+ 1.
+ JSP versus FreeMarker?
+
+
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>We compare FreeMarker with the JSP 2.0 + JSTL combo
+ here.</p>
+
+ <p>FreeMarker Pros:</p>
+
+ <ul>
+ <li>
+ <p>FreeMarker is not tied to Servlets or networking/Web; it
+ is just a class library to generate text output by merging a
+ template with Java objects (the data-model). You can execute
+ templates anywhere and anytime; no HTTP request forwarding or
+ similar tricks needed, no Servlet environment needed at all.
+ Because of this you can easily integrate it into any
+ system.</p>
+ </li>
+
+ <li>
+ <p>Terser syntax. Consider this JSP (assuming
+ <code class="inline-code"><%@ taglib prefix="c"
+ uri="http://java.sun.com/jsp/jstl/core"
+ %></code>):</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><c:if test="${t}">
+ True
+</c:if>
+
+<c:choose>
+ <c:when test="${n == 123}">
+ Do this
+ </c:when>
+ <c:otherwise>
+ Do that
+ </c:otherwise>
+</c:choose>
+
+<c:forEach var="i" items="${ls}">
+- ${i}
+</c:forEach></pre></div>
+
+ <p>and the equivalent FTL:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><#if t>
+ True
+</#if>
+
+<#if n == 123>
+ Do this
+<#else>
+ Do that
+</#if>
+
+<#list ls as i>
+- ${i}
+</#list></pre></div>
+ </li>
+
+ <li>
+ <p>No servlet specific scopes and other highly technical
+ things in templates (unless, of course, you expose them into
+ the data-model deliberately). It was made for MVC from the
+ beginning, it focuses only on the presentation.</p>
+ </li>
+
+ <li>
+ <p>You can load the templates from anywhere; from the class
+ path, from a data-base, etc.</p>
+ </li>
+
+ <li>
+ <p>Locale-sensitive number and date formatting by default.
+ When you output for a human audience, all you need to do is
+ just write <code class="inline-code">${x}</code> rather than
+ <code class="inline-code"><fmt:formatNumber value="${x}"
+ /></code>.</p>
+ </li>
+
+ <li>
+ <p>Easier to define ad-hoc macros and functions.</p>
+ </li>
+
+ <li>
+ <p>No sweeping errors under the carpet. Missing variables
+ and <code class="inline-code">null</code>-s will not silently default to
+ <code class="inline-code">0</code>/<code class="inline-code">false</code>/empty-string,
+ but cause error. <a href="#faq_picky_about_missing_vars">See more about this
+ here...</a></p>
+ </li>
+
+ <li>
+ <p>"Object wrapping". This lets you show the
+ objects to templates in a customized, presentation oriented
+ way (e.g. <a href="xgui_imperative_learn.html">see
+ here</a> how a W3C DOM nodes can be seen by templates using
+ this technology.)</p>
+ </li>
+
+ <li>
+ <p>Macros and functions are just variables, so they can be
+ easily passed around as parameter values, put into the
+ data-model, etc., just like any other values.</p>
+ </li>
+
+ <li>
+ <p>Virtually unnoticeable delay when visiting a page for
+ the first time (or after it was changed), because no expensive
+ compilation happens.</p>
+ </li>
+ </ul>
+
+ <p>FreeMarker Cons:</p>
+
+ <ul>
+ <li>
+ <p>Not a "standard". There are fewer tools and
+ IDE integrations, fewer developers knows it and there's much
+ less industry support in general. (However, most JSP tag
+ libraries can work in FreeMarker templates with the proper
+ setup, unless they are base on <code class="inline-code">.tag</code>
+ files.)</p>
+ </li>
+
+ <li>
+ <p>Its syntax doesn't follow the HTML/XML rules apart from
+ some visual similarity, which is confusing for new users (it's
+ the price of the terseness). JSP doesn't follow it either, but
+ it's closer to it.</p>
+ </li>
+
+ <li>
+ <p>Since macros and functions are just variables, incorrect
+ directive and parameter names and missing required parameters
+ can be detected only on runtime.</p>
+ </li>
+
+ <li>
+ <p>Doesn't work with JSF. (It could work technically, but
+ nobody has implemented that yet.)</p>
+ </li>
+ </ul>
+
+ <p>You may read this if you are considering replacing JSP with
+ FreeMarker in an existing application or in a legacy framework
+ that only supports JSP: <a href="pgui_misc_servlet.html#pgui_misc_servlet_model2">Programmer's Guide/Miscellaneous/Using FreeMarker with servlets/Using FreeMarker for "Model 2"</a></p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_picky_about_missing_vars">
+ 2.
+ Why is FreeMarker so picky about <code class="inline-code">null</code>-s
+ and missing variables, and what to do with it?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>To recapitulate what's this entry is about: FreeMarker by
+ default treats an attempt to access a non-existent variable or a
+ <code class="inline-code">null</code> value (<a href="#faq_null">this two
+ is the same for FreeMarker</a>) as error, which aborts the
+ template execution.</p>
+
+ <p>First of all, you should understand the reason of being
+ picky. Most scripting languages and template languages are rather
+ forgiving with missing variables (and with
+ <code class="inline-code">null</code>-s), and they usually treat them as empty
+ string and/or 0 and/or logical false. This behavior has several
+ problems:</p>
+
+ <ul>
+ <li>
+ <p>It potentially hides accidental mistakes, like a typo in
+ a variable name, or when the template author refers to a
+ variable that the programmer doesn't put into the data-model
+ for that template, or for which the programmer uses a
+ different name. Humans are prone to do such mistakes, while
+ computers are not, so missing this opportunity that the
+ template engine can show these errors is a bad business. Even
+ if you very carefully check the output of the templates during
+ development, it is easy to look over mistakes like
+ <code class="inline-code"><#if hasWarnigs><em class="code-color">print warnings
+ here...</em></#if></code>, which would then
+ silently never print the warnings, since you have mistyped the
+ variable name (have you noticed it?). Also think about
+ maintenance, when you later modify your application; probably
+ you will not re-check templates (many applications has
+ hundreds of them) that carefully each time, for all possible
+ scenarios. Unit tests typically doesn't cover web page content
+ very good either (if you have them at all...); they mostly
+ only check certain manually set patterns in the web page, so
+ they will often gloss though changes that are actually bugs.
+ But if the page fails with exception, that's something human
+ testers will notice and unit test will notice (as the whole
+ page will fail), and in production the maintainers will notice
+ (assuming somebody check error logs).</p>
+ </li>
+
+ <li>
+ <p>Makes dangerous assumptions. The script language or
+ template engine knows nothing about the application domain, so
+ when it decides the value of something that it doesn't know to
+ be 0/false, it is a quite irresponsible and arbitrary thing.
+ Just because it's not know what's your current balance at your
+ bank, can we just say it's $0? Just because it is not known if
+ a patient has penicillin allergy, can we just say he/she
+ doesn't have it? Just consider the implications of such
+ mistakes. Showing an error page is often better than showing
+ incorrect information that looks good, leading to bad
+ decisions on the user side.</p>
+ </li>
+ </ul>
+
+ <p>Being not picky is mostly sweeping under the carpet in this
+ case (not facing the problems), which of course most people feels
+ more convenient, but still, we believe that in most cases being
+ strict will save your time and increase your software quality on
+ the long run.</p>
+
+ <p>On the other hand, we recognize that there are cases where
+ you don't want FreeMarker to be that picky for good reason, and
+ there is solution for them:</p>
+
+ <ul>
+ <li>
+ <p>It's often normal that your data-model contains
+ <code class="inline-code">null</code>-s or have optional variables. In such
+ cases use <a href="dgui_template_exp.html#dgui_template_exp_missing">these
+ operators</a>. If you use them too often, try to rethink
+ your data-model, because depending on them too much won't just
+ make the templates too verbose, but increases the probability
+ of hiding errors and printing arbitrary incorrect output (for
+ the reasons described earlier).</p>
+ </li>
+
+ <li>
+ <p>In some application you may rather want to show an
+ incomplete/damaged page than an error page. In this case you
+ can <a href="pgui_config_errorhandling.html">use another
+ error handler</a> than the default one. A custom error
+ handler can skip the problematic part, or show an error
+ indicator there, instead of aborting the whole page rendering.
+ Note, however, that although the error handlers don't give
+ arbitrary default values to variables, for pages that show
+ critical information it's maybe still better to show an error
+ page.</p>
+ </li>
+
+ <li>
+ <p>If the pages contain parts that aren't critically
+ important (like some side bars), another feature you may
+ interested in is <a href="ref_directive_attempt.html">the
+ <code>attempt</code>/<code>recover</code>
+ directives</a>.</p>
+ </li>
+ </ul>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_number_grouping">
+ 3.
+ Why does FreeMarker print the numbers with strange
+ formatting (as 1,000,000 or 1�000�000 instead of 1000000)?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>FreeMarker uses the locale-sensitive number formatting
+ capability of the Java platform. The default number format for
+ your locale may uses grouping or other formatting. If you don't
+ want that, you have to override the number format suggested by the
+ Java platform with the <code class="inline-code">number_format</code> <a href="pgui_config_settings.html">FreeMarker setting</a>. For
+ example:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-unspecified">cfg.setNumberFormat("0.######"); // now it will print 1000000
+// where cfg is a freemarker.template.Configuration object</pre></div>
+
+ <p>Note however than humans often find it hard to read big
+ numbers without grouping separator. So in general it is
+ recommended to keep them, and in cases where the numbers are for
+ ''computer audience'' (which is confused on the grouping
+ separators), use the <a href="ref_builtins_number.html#ref_builtin_c"><code>c</code> built-in</a>. For
+ example:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><a href="/shop/productdetails?id=${<strong>product.id?c</strong>}">Details...</a></pre></div>
+
+ <p>For computer audience you need <code class="inline-code">?c</code> anyway,
+ as the decimal separators can also wary depending on the
+ locale.</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_number_decimal_point">
+ 4.
+ Why does FreeMarker print bad decimal and/or grouping
+ separator symbol (as 3.14 instead of 3,14)?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Different countries use different decimal/grouping separator
+ symbols. If you see incorrect symbols, then probably your locale
+ is not set properly. Set the default locale of the JVM or override
+ the default locale with the <code class="inline-code">locale</code> <a href="pgui_config_settings.html">FreeMarker setting</a>. For
+ example:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-unspecified">cfg.setLocale(java.util.Locale.ITALY);
+// where cfg is a freemarker.template.Configuration object</pre></div>
+
+ <p>However, sometimes you want to output a number not for human
+ audience, but for "computer audience" (like you want
+ to print a size in CSS), in which case you must use dot as decimal
+ separator, regardless of the locale (language) of the page. For
+ that use the <a href="ref_builtins_number.html#ref_builtin_c"><code>c</code>
+ built-in</a>, for example:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template">font-size: ${<strong>fontSize?c</strong>}pt;</pre></div>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_number_boolean_formatting">
+ 5.
+ Why does FreeMarker give an error when I try to print a
+ boolean like <code class="inline-code">${aBoolean}</code>, and how to fix
+ it?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Unlike numbers, booleans has no commonly accepted format,
+ not even a common format within the same page. Like when you show
+ on a HTML page if a product is washable, you will hardly want to
+ show for the visitor "Washable: true", but rather "Washable: yes".
+ So we force the template author (by <code class="inline-code">${washable}</code>
+ causing error) to find out with his human knowledge how the
+ boolean value should be shown at the given place. The common way
+ of formatting a boolean is like <code class="inline-code">${washable?string("yes",
+ "no")}</code>, <code class="inline-code">${caching?string("Enabled",
+ "Disabled")}</code>, <code class="inline-code">${heating?string("on",
+ "off")}</code>, etc.</p>
+
+ <p>However, there are two cases where this gets
+ impractical:</p>
+
+ <ul>
+ <li>
+ <p>When printing boolean to generate computer language
+ output, and hence you want
+ <code class="inline-code">true</code>/<code class="inline-code">false</code>, use
+ <code class="inline-code">${<em class="code-color">someBoolean</em>?c}</code>.
+ (This requires at least FreeMarker 2.3.20. Before that, the
+ common practice was writing
+ <code class="inline-code">${<em class="code-color">someBoolean</em>?string}</code>,
+ however that's dangerous because its output depends on the
+ current boolean format setting, whose default is
+ <code class="inline-code">"true"</code>/<code class="inline-code">"false"</code>.)</p>
+ </li>
+
+ <li>
+ <p>When you have format most of the booleans on the same
+ way. In this case you can set the
+ <code class="inline-code">boolean_format</code> setting
+ (<code class="inline-code">Configuration.setBooleanFormat</code>) to reflect
+ that, and then since FreeMarker 2.3.20 you can just write
+ <code class="inline-code">${<em class="code-color">someBoolean</em>}</code>.
+ (Note that this doesn't work for
+ <code class="inline-code">true</code>/<code class="inline-code">false</code> though - you
+ have to use <code class="inline-code">?c</code> there.)</p>
+ </li>
+ </ul>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_template_not_found">
+ 6.
+ FreeMarker can't find my templates
+ (<code class="inline-code">TemplateNotFoundException</code> or
+ <code class="inline-code">FileNotFoundException</code>, "Template not
+ found" error message)
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>First of all, you should know that FreeMarker doesn't load
+ templates from file system paths directly. Instead, it uses a
+ simple virtual file system that might reads non-filesystem
+ resources (templates from inside jar-s, from inside a database
+ table, etc.). What that virtual file is decided by a configuration
+ setting,
+ <code class="inline-code">Configuration.setTemplateLoader(TemplateLoader)</code>.
+ Even if the <code class="inline-code">TemplateLoader</code> your are using maps
+ to the file system, it will have a base directory that contains
+ all the templates, and that will be the root of your virtual file
+ system that you can't reach out from (i.e., absolute paths will be
+ still relative to the virtual file system root).</p>
+
+ <p>Tips to solve the problem:</p>
+
+ <ul>
+ <li>
+ <p>If you are the one who configure FreeMarker, be sure
+ that you set a proper
+ <code class="inline-code">TemplateLoader</code>.</p>
+ </li>
+
+ <li>
+ <p>Otherwise see if the template-not-found error's message
+ contains the description of the
+ <code class="inline-code">TemplateLoader</code> used. If it doesn't, you are
+ using an old FreeMarker version, so update it. Getting
+ <code class="inline-code">FileNotFoundException</code> instead of
+ <code class="inline-code">TemplateNotFoundException</code> is also a sign of
+ that, and so you will get less helpful error messages. (If the
+ <code class="inline-code">TemplateLoader</code> in the error message is like
+ <code class="inline-code">foo.SomeTemplateLoader@64f6106c</code> and so
+ doesn't show some relevant parameters, you may should ask the
+ author to define a nicer
+ <code class="inline-code">toString()</code>.)</p>
+ </li>
+
+ <li>
+ <p>A frequent mistake is using a
+ <code class="inline-code">FileTemplateLoader</code> for a Servlet-based web
+ application, instead of a
+ <code class="inline-code">WebappTemplateLoader</code>. It may works in one
+ environment, but not in another, as the Servlet specification
+ makes no promises about your resources being accessible as
+ plain files, not even when the <code class="inline-code">war</code> file is
+ extracted.</p>
+ </li>
+
+ <li>
+ <p>Know that when you are including/importing a template
+ from another template, if you don't start the template name
+ with <code class="inline-code">/</code>, it will be interpreted relatively
+ to the directory of the including template. The error message
+ contains the full (resolved) name, so you should notice this
+ there.</p>
+ </li>
+
+ <li>
+ <p>Check that you aren't using <code class="inline-code">\</code>
+ (backslash) instead of <code class="inline-code">/</code> (slash).
+ (FreeMarker 2.3.22 and later will warn you about that in the
+ error message.)</p>
+ </li>
+
+ <li>
+ <p>As a last resort, turn on debug level logging (in the
+ logging framework that you are using) for the category
+ <code class="inline-code">freemarker.cache</code>, to see more of what's
+ going on.</p>
+ </li>
+ </ul>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_check_version">
+ 7.
+ The documentation writes about feature
+ <em>X</em>, but it seems that FreeMarker doesn't
+ know that, or it behaves in a different way as documented, or a
+ bug that was supposedly fixed is still present.
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Are you sure that you are using the documentation written
+ for the same version of FreeMarker that you actually use?
+ Especially, note that our online documentation is for the latest
+ stable FreeMarker release. You may use an older release; update
+ it.</p>
+
+ <p>Are you sure that the Java class loader finds the same
+ <code class="inline-code">freemarker.jar</code> that you expect to use? Maybe
+ there is an older version of <code class="inline-code">freemarker.jar</code>
+ around, which shadows the never. To check this, try to print the
+ version number in a template with <code class="inline-code">${.version}</code>.
+ (If it dies with "Unknown built-in variable: version"
+ error message, then you use a very, very old release.).</p>
+
+ <p>If you suspect that the problem is that you have multiple
+ <code class="inline-code">freemarker.jar</code>-s, the typical culprit is that
+ some module has a Maven or Ivy dependency with the old
+ <code class="inline-code">freemarker</code> group ID, as opposed to the more
+ modern <code class="inline-code">org.freemarker</code> group ID. Because of the
+ different group ID-s these aren't seen as conflicting artifacts by
+ Maven or Ivy, and so both version gets in. In this case you have
+ to exclude the <code class="inline-code">freemarker</code> dependency.</p>
+
+ <p>If you think that the documentation or FreeMarker is wrong,
+ please report it using the bug tracker, or the mailing list. Thank
+ you!</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_alternative_syntax">
+ 8.
+ The <code class="inline-code"><</code> and <code class="inline-code">></code> of
+ FreeMarker tags confuses my editor or the XML parser. What to
+ do?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Starting from FreeMarker 2.3.4 you can use
+ <code class="inline-code">[</code> and <code class="inline-code">]</code> instead of
+ <code class="inline-code"><</code> and <code class="inline-code">></code>. For more
+ details <a href="dgui_misc_alternativesyntax.html">read
+ this...</a></p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_legal_variable_names">
+ 9.
+ What are the legal variable names?
+
+
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>FreeMarker has no limitations regarding the characters used
+ in variable names, nor regarding the length of the variable names,
+ but for your convenience try to chose variable names that can be
+ used with the simple variable reference expressions (see it <a href="dgui_template_exp.html#dgui_template_exp_var_toplevel">here</a>). If you have
+ to choose a more extreme variable name, that's not a big problem
+ either: <a href="#faq_strange_variable_name">see
+ here</a>.</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_strange_variable_name">
+ 10.
+ How can I use variable names (macro name, parameter name)
+ that contain minus sign (<code class="inline-code">-</code>), colon
+ (<code class="inline-code">:</code>), dot (<code class="inline-code">.</code>), or or other
+ special characters?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>If you have a variable with strange name like
+ "foo-bar", FreeMarker will misunderstand what you
+ mean if you just use it like in <code class="inline-code">${foo-bar}</code>. In
+ this case, it will believe that you want to subtract the value of
+ <code class="inline-code">bar</code> from <code class="inline-code">foo</code>. This FAQ entry
+ explains how to handle situations like this.</p>
+
+ <p>First of all it should be clear that these are just
+ syntactical problems, as otherwise FreeMarker has no limitations
+ regarding the characters used in variable names, nor regarding the
+ length of them.</p>
+
+ <p>If the special character is one of minus sign
+ (<code class="inline-code">-</code>, UCS 0x2D) or dot (<code class="inline-code">.</code>, UCS
+ 0x2E) or colon (<code class="inline-code">:</code>, UCS 0x3A), then all you have
+ to do is putting a backslash (<code class="inline-code">\</code>) before these
+ characters, like in <code class="inline-code">foo\-bar</code> (since FreeMarker
+ 2.3.22). Then FreeMarker will know that you didn't mean the
+ operator with the same symbol. This works everywhere where you
+ specify unquoted identifiers, like for macro and function names,
+ parameter names, and all kind of variable references in general.
+ (Note that these escapes only work in identifiers, not in string
+ literals.)</p>
+
+ <p>When the special character is not one of minus sign, dot, or
+ colon, then it gets trickier. Let's say the problematic variable
+ name is "a+b". Then:</p>
+
+ <ul>
+ <li>
+ <p>If you want to read the variable: If it's a subvariable
+ of something, you can write
+ <code class="inline-code">something["a+b"]</code> (remember,
+ <code class="inline-code">something.x</code> is equivalent to
+ <code class="inline-code">something["x"])</code>. If it's a top-level
+ variable, those are accessible through the special hash
+ variable ,<code class="inline-code">.vars</code>, so you can write
+ <code class="inline-code">.vars["a+b"]</code>. Naturally, this trick works
+ with macro and function invocations too:
+ <code class="inline-code"><@.vars["a+b"]/></code>,
+ <code class="inline-code">.vars["a+b"](1, 2)</code>.</p>
+ </li>
+
+ <li>
+ <p>If you want to create or modify the variable: All
+ directives that let you create or modify a variable (such as
+ <code class="inline-code">assign</code>, <code class="inline-code">local</code>,
+ <code class="inline-code">global</code>, <code class="inline-code">macro</code>,
+ <code class="inline-code">function</code>, etc.) allows the quotation of the
+ destination variable name. For example, <code class="inline-code"><#assign
+ foo = 1></code> is the same as <code class="inline-code"><#assign
+ "foo" = 1></code>. So you can write things like
+ <code class="inline-code"><#assign "a+b" = 1></code> and
+ <code class="inline-code"><#macro "a+b"></code>.</p>
+ </li>
+
+ <li>
+ <p>Unfortunately, you can't use such a variable name (that
+ contains special characters other than <code class="inline-code">-</code>,
+ <code class="inline-code">.</code> and <code class="inline-code">:</code>) as macro
+ parameter name.</p>
+ </li>
+ </ul>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_jsp_custom_tag_syntax">
+ 11.
+ Why do I get "java.lang.IllegalArgumentException: argument
+ type mismatch" when I try to use <em>X</em> JSP
+ custom tag?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Fist of all, update FreeMarker, because 2.3.22 and later
+ gives a much more helpful error message, that pretty much answers
+ the question. Anyway, the reason is as follows. On JSP pages you
+ quote all parameter (attribute) values, it does not mater if the
+ type of the parameter is string or boolean or number. But since
+ custom tags are accessible in FTL templates as plain user-defined
+ FTL directives, you have to use the FTL syntax rules inside the
+ custom tags, not the JSP rules. Thus, according to FTL rules, you
+ must not quote boolean and numerical parameter values, or they are
+ interpreted as string values, and this will cause a type mismatch
+ error when FreeMarker tries to pass the value to the custom tag
+ that expects non-string value.</p>
+
+ <p>For example, the <code class="inline-code">flush</code> parameter to
+ Struts Tiles <code class="inline-code">insert</code> tag is boolean. In JSP the
+ correct syntax was:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><tiles:insert page="/layout.jsp" <strong>flush="true"</strong>/>
+<em>...</em></pre></div>
+
+ <p>but in FTL you should write:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><@tiles.insert page="/layout.ftl" <strong>flush=true</strong>/>
+<em>...</em></pre></div>
+
+ <p>Also, for similar reasons, this is wrong:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><tiles:insert page="/layout.jsp" <strong>flush="${needFlushing}"</strong>/>
+<em>...</em></pre></div>
+
+ <p>and you should write:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><tiles:insert page="/layout.jsp" <strong>flush=needFlushing</strong>/>
+<em>...</em></pre></div>
+
+ <p>(Not <code class="inline-code">flush=${needFlushing}</code>!)</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_servlet_include">
+ 12.
+ How to include other resources in a way as
+ <code class="inline-code">jsp:include</code> does it?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Not with <code class="inline-code"><#include ...></code>, as that
+ just includes another FreeMarker template without involving the
+ Servlet container.</p>
+
+ <p>Since the inclusion method you look for is Servlet-related,
+ and pure FreeMarker is unaware of Servlets or even HTTP, it's the
+ Web Application Framework that decides if you can do this and if
+ so how. For example, in Struts 2 you can do this like this:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><@s.include value="/WEB-INF/just-an-example.jspf" /></pre></div>
+
+ <p>If the FreeMarker support of the Web Application Framework
+ is based on
+ <code class="inline-code">freemarker.ext.servlet.FreemarkerServlet</code>, then
+ you can also do this (since FreeMarker 2.3.15):</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><@include_page path="/WEB-INF/just-an-example.jspf" /></pre></div>
+
+ <p>but if the Web Application Framework provides its own
+ solution, then you may prefer that, after all it may does
+ something special.</p>
+
+ <p>For more information about <code class="inline-code">include_page</code>
+ <a href="pgui_misc_servlet.html#pgui_misc_servlet_include">read
+ this...</a></p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_parameter_unwrapping">
+ 13.
+ How can I get the parameters to my
+ plain-Java-method/<code class="inline-code">TemplateMethodModelEx</code>/<code class="inline-code">TemplateTransformModel</code>/<code class="inline-code">TemplateDirectiveModel</code>
+ implementation as plain
+ <code class="inline-code">java.lang.*</code>/<code class="inline-code">java.util.*</code>
+ objects?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Unfortunately, there is no simple general-purpose solution
+ for this problem. The problem is that FreeMarker object wrapping
+ is very flexible, which is good when you access variables from
+ templates, but makes unwrapping on the Java side a tricky
+ question. For example, it is possible to wrap a
+ non-<code class="inline-code">java.util.Map</code> object as
+ <code class="inline-code">TemplateHashModel</code> (FTL hash variable). But
+ then, it can't be unwrapped to <code class="inline-code">java.util.Map</code>,
+ since there is no wrapped <code class="inline-code">java.util.Map</code> around
+ at all.</p>
+
+ <p>So what to do then? Basically there are two cases:</p>
+
+ <ul>
+ <li>
+ <p>Directives and methods that are written for presentation
+ purposes (like kind of "tools" for helping
+ FreeMarker templates) should declare their arguments as
+ <code class="inline-code">TemplateModel</code>-s and the more specific sub
+ interfaces of that. After all, the object wrapping is about
+ transforming the data-model to something that serves the
+ purpose of the presentation layer, and these methods are part
+ of the presentation layer. If you still need a plain Java type
+ there, you may turn to the
+ <code class="inline-code">ObjectWrapperAndUnwrapper</code> interface of the
+ current <code class="inline-code">ObjectWrapper</code> (can be get with
+ <code class="inline-code">Environment.getObjectWrapper()</code>).</p>
+ </li>
+
+ <li>
+ <p>Methods that are not for presentation related tasks (but
+ for business logic and like) should be implemented as plain
+ Java methods, and should not use any FreeMarker specific
+ classes at all, since according the MVC paradigm they must be
+ independent of the presentation technology (FreeMarker). If
+ such a method is called from a template, then it is the
+ responsibility of the <a href="pgui_datamodel_objectWrapper.html">object wrapper</a>
+ to ensure the conversion of the arguments to the proper type.
+ If you use the <a href="pgui_datamodel_objectWrapper.html#pgui_datamodel_defaultObjectWrapper"><code>DefaultObjectWrapper</code></a>
+ or the <a href="pgui_misc_beanwrapper.html"><code>BeansWrapper</code></a>
+ then this will happen automatically. For
+ <code class="inline-code">DefaultObjectWrapper</code>, this mechanism works
+ much better, if you <a href="pgui_datamodel_objectWrapper.html#topic.defaultObjectWrapperIcI">set its
+ <code>incompatibleImprovements</code> to
+ 2.3.22</a>.</p>
+ </li>
+ </ul>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_nonstring_keys">
+ 14.
+ Why I can't use non-string key in the
+ <code class="inline-code">myMap[myKey]</code> expression? And what to do
+ now?
+
+
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>The "hash" type of the FreeMarker Template
+ Language (FTL) is not the same as Java's <code class="inline-code">Map</code>.
+ FTL's hash is an associative array too, but it uses string keys
+ exclusively. This is because it was introduced for sub variables
+ (as <code class="inline-code">password</code> in
+ <code class="inline-code">user.password</code>, which is the same as
+ <code class="inline-code">user["password"]</code>), and variable names are
+ strings.</p>
+
+ <p>If you only need to list the key-value pairs of a
+ <code class="inline-code">Map</code>, you can just write something like
+ <code class="inline-code"><#list myMap as k, v>${k}:
+ ${v}</#list></code> (see more about <a href="ref_directive_list.html#ref.directive.list">the <code>list directive</code>
+ here</a>). This enumerates the <code class="inline-code">Map</code> entries,
+ and supports non-string keys. This requires FreeMarker 2.3.25 or
+ later. (If for some reason you can't upgrade to 2.3.25, you can
+ use the Java API of <code class="inline-code">Map</code> instead, like
+ <code class="inline-code"><#list myMap?api.entrySet() as kvp>${kvp.key}:
+ ${kvp.value}</#list></code>.)</p>
+
+ <p>If you need to do more than listing, you will have to turn
+ to the Java API of the <code class="inline-code">Map</code>. You can do it like
+ this: <code class="inline-code">myMap?api.get(nonStringKey)</code>. However, for
+ <code class="inline-code">?api</code> to be enabled, you may need to configure
+ FreeMarker a bit (<a href="ref_builtins_expert.html#ref_buitin_api_and_has_api">see
+ more here</a>).</p>
+
+ <p>Note that as Java's <code class="inline-code">Map</code> is particular
+ about the exact class of the key, at least for numerical keys
+ calculated inside the templates you will have to cast them to the
+ proper Java type, otherwise the item will not be found. For
+ example if you use <code class="inline-code">Integer</code> keys in a Map, then
+ you should write <code class="inline-code">${myMap.get(numKey?int)}</code>. This
+ is because of FTL's deliberately simplified type system has only a
+ single numerical type, while Java distinguishes a lot of numerical
+ types. Note that the casting is not needed when the key value
+ comes directly from the data-model (i.e., you didn't modified its
+ value with arithmetical calculations in the template), including
+ the case when it's the return value of a method, and it was of the
+ proper class before wrapping, because then the result of the
+ unwrapping will be of the original type.</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_simple_map">
+ 15.
+ When I list the contents of a map (a hash) with
+ <code class="inline-code">?keys</code>/<code class="inline-code">?values</code>, I get the
+ <code class="inline-code">java.util.Map</code> methods mixed with the real map
+ entries. Of course, I only want to get the map entries.
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Certainly you are using pure <code class="inline-code">BeansWrapper</code>
+ as your object wrapper (instead of the default,
+ <code class="inline-code">DefaultObjectWrapper</code>), or a custom subclass of
+ it, and the <code class="inline-code">simpleMapWrapper</code> property of that
+ is left to <code class="inline-code">false</code>. Unfortunately, that's the
+ default of <code class="inline-code">BeansWrapper</code> (for backward
+ compatibility), so you have to explicitly set it to
+ <code class="inline-code">true</code> where you instantiate it. Also, at least
+ since 2.3.22, applications should just use
+ <code class="inline-code">DefaultObjectWrapper</code> (with <a href="pgui_datamodel_objectWrapper.html#topic.defaultObjectWrapperIcI">its
+ <code>incompatibleImprovements</code> set to at least
+ 2.3.22</a> - that's especially important if you are switching
+ from pure <code class="inline-code">BeansWrapper</code>), which never had this
+ problem.</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_modify_seq_and_map">
+ 16.
+ How can I modify sequences (lists) and hashes (maps) in
+ FreeMarker templates?
+
+
+
+
+
+
+
+
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>First of all, you may don't want to modify the
+ sequence/hash, just concatenate (add) two or more of them, which
+ results in a new sequence/hash, rather than modifying an existing
+ one. In this case use the <a href="dgui_template_exp.html#dgui_template_exp_sequenceop_cat">sequence
+ concatenation</a> and <a href="dgui_template_exp.html#dgui_template_exp_hashop_cat">hash concatenation
+ operators</a>. Also, you may use the <a href="dgui_template_exp.html#dgui_template_exp_seqenceop_slice">subsequence
+ operator</a> instead of removing sequence items. However, be
+ aware of the performance implications: these operations are fast,
+ but the hashes/sequences that are the result of many subsequent
+ applications of these operations (i.e., when you use the result of
+ the operation as the input of yet another operation, and so on)
+ will be slow to read.</p>
+
+ <p>Now if you still want to modify sequences/hashes, then read
+ on...</p>
+
+ <p>The FreeMarkes Template Language doesn't support the
+ modification of sequences/hashes. It's for displaying already
+ calculated things, not for calculating data. Keep templates
+ simple. But don't give it up, you will see some advices and tricks
+ bellow.</p>
+
+ <p>The best is if you can divide the work between the
+ data-model builder program and the template so that the template
+ doesn't need to modify sequences/hashes. Maybe if you rethink your
+ data-model, you will realize this is possible. But, seldom there
+ are cases where you need to modify sequences/hashes for some
+ complex but purely presentation related algorithms. It seldom
+ happens, so think twice whether that calculation (or parts of it)
+ rather belongs to the data-model domain than to the presentation
+ domain. Let's assume you are sure it belongs to the presentation
+ domain. For example, you want to display a keyword index on some
+ very smart way, whose algorithm need you to create and write some
+ sequence variables. Then you should do something like this (ugly
+ situations has ugly solutions...):</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><#assign caculatedResults =
+ 'com.example.foo.SmartKeywordIndexHelper'?new().calculate(keywords)>
+<#-- some simple algorithms comes here, like: -->
+<ul>
+ <#list caculatedResults as kw>
+ <li><a href="${kw.link}">${kw.word}</a>
+ </#list>
+</ul></pre></div>
+
+ <p>That is, you move out the complex part of the presentation
+ task from the template into Java code. Note that it doesn't affect
+ the data-model, so the presentation is still kept separated from
+ other the other application logic. Of course the drawback is that
+ for this the template author will need the help of a Java
+ programmer, but for complex algorithms that's probably needed
+ anyway.</p>
+
+ <p>Now, if you still say you need to modify sequences/hashes
+ directly with the FreeMarker template, here are some solutions,
+ but please read the warning after them:</p>
+
+ <ul>
+ <li>
+ <p>You can access the Java API of a
+ <code class="inline-code">java.util.Map</code> with the help of the
+ <code class="inline-code">api</code> built-in, like
+ <code class="inline-code">myMap?api.put(11, "eleven")</code>. You will need
+ to get a <code class="inline-code">Map</code> from somewhere though (an FTL
+ hash literal like <code class="inline-code">{}</code> won't suffice, as it's
+ read only and doesn't support <code class="inline-code">api</code> either).
+ For example, you could expose a Java method or
+ <code class="inline-code">TemplateMethodModelEx</code> to the template that
+ returns a <code class="inline-code">new LinkeHashMap()</code>, so you can do
+ <code class="inline-code"><#assign myMap =
+ utils.newLinkedHashMap()></code>.</p>
+ </li>
+
+ <li>
+ <p>You can write a <code class="inline-code">TemplateMethodModelEx</code>
+ and <code class="inline-code">TemplateDirectiveModel</code> implementation
+ that can modify certain types of sequences/hashes. Just
+ certain types, because
+ <code class="inline-code">TemplateSequenceModel</code> and
+ <code class="inline-code">TemplateHashModel</code> doesn't have methods for
+ modification, so you will need the sequence or hash to
+ implement some additional methods. An example of this solution
+ can be seen in FMPP. It allows you to do things like this
+ (<code class="inline-code">pp</code> stores the services provided by FMPP
+ for templates):</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><#assign a = pp.newWritableSequence()>
+<@pp.add seq=a value="red" /></pre></div>
+
+ <p>The <code class="inline-code">pp.add</code> directive works only with
+ sequences that were created with
+ <code class="inline-code">pp.newWritableSequence()</code>. So for example
+ the template author can't modify a sequence that comes from
+ the data-model with this.</p>
+ </li>
+
+ <li>
+ <p>A sequence can have some methods/directives if you use a
+ customized wrapper (so you can write something like
+ <code class="inline-code"><@myList.append foo /></code>).</p>
+ </li>
+ </ul>
+
+ <p>But beware, these solutions have a problem: The <a href="dgui_template_exp.html#dgui_template_exp_sequenceop_cat">sequence
+ concatenation</a>, <a href="dgui_template_exp.html#dgui_template_exp_seqenceop_slice">sequence slice</a>
+ operator (like <code class="inline-code">seq[5..10]</code>) and
+ <code class="inline-code">?reverse</code> do not copy the original sequence,
+ just wraps it (for efficiency), so the resulting sequence will
+ change if the original sequence is changed later (an abnormal
+ aliasing effect). The same problem exists with the result of <a href="dgui_template_exp.html#dgui_template_exp_hashop_cat">hash concatenation</a>;
+ it just wraps the two hashes, so the resulting hash will magically
+ change if you modify the hashes you have added earlier. As a
+ work-around, after you did the above problematic operations,
+ either be sure you will not modify the objects that were used as
+ input, or create a copy of the result with a method provided by
+ the solution described in above two points (e.g. in FMPP you could
+ do <code class="inline-code"><#assign b =
+ pp.newWritableSequence(a[5..10])></code> and
+ <code class="inline-code"><#assign c = pp.newWritableHash(hashA +
+ hashB)></code>). Of course this is easy to miss... so again,
+ rather try to build the data-model so you will not need to modify
+ collections, or use a presentation task helper class as was shown
+ earlier.</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_null">
+ 17.
+ What about <code class="inline-code">null</code> and the FreeMarker
+ template language?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>The FreeMarker template language doesn't know the Java
+ language <code class="inline-code">null</code> at all. It doesn't have
+ <code class="inline-code">null</code> keyword, and it can't test if something is
+ <code class="inline-code">null</code> or not. When it technically faces with a
+ <code class="inline-code">null</code>, it treats it exactly as a missing
+ variable. For example, both if <code class="inline-code">x</code> is
+ <code class="inline-code">null</code> in the data-model and if it's not present
+ at all, <code class="inline-code">${x!'missing'}</code> will print
+ "missing", you can't tell the difference. Also, if
+ for example you want to test if a Java method has returned
+ <code class="inline-code">null</code>, just write something like
+ <code class="inline-code"><#if foo.bar()??></code>.</p>
+
+ <p>You may interested in the rationale behind this. From the
+ viewpoint of the presentation layer a <code class="inline-code">null</code> and
+ non-existent thing is almost always the same. The difference
+ between this two is usually just a technical detail, which is
+ rather the result of implementation details than of the
+ application logic. That you can't compare something to
+ <code class="inline-code">null</code> (unlike in Java); it doesn't make sense to
+ compare something with <code class="inline-code">null</code> in a template,
+ since the template language doesn't do identity comparison (like
+ the Java <code class="inline-code">==</code> operator when you compare two
+ objects) but the more common sense value comparison (like Java's
+ <code class="inline-code">Object.equals(Object)</code>; that doesn't work with
+ <code class="inline-code">null</code> either). And how could FreeMarker tell if
+ something concrete equals with something that is missing and thus
+ unknown? Or if two missing (unknown) things are equal? Of course
+ these questions can't be answered.</p>
+
+ <p>There is at least one problem with this
+ <code class="inline-code">null</code>-unaware approach. When you call a Java
+ method from a template, you may want to pass a
+ <code class="inline-code">null</code> value as argument (since the method was
+ designed to be used in Java language, where the concept of
+ <code class="inline-code">null</code> is known). In this case you can exploit a
+ bug of FreeMarker (that we will not fix until we provide a correct
+ solution for passing <code class="inline-code">null</code> values to a method):
+ if you specify a missing variable as the argument, then it will
+ not cause an error, but a <code class="inline-code">null</code> will be passed
+ to the method instead. Like <code class="inline-code">foo.bar(nullArg)</code>
+ will call the <code class="inline-code">bar</code> method with
+ <code class="inline-code">null</code> as argument, assuming that there is no
+ variable exists with "nullArg" name.</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_capture">
+ 18.
+ How can I use the output of a directive (macro) in
+ expressions (as a parameter to another directive)?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>Capture the output into a variable with the
+ <code class="inline-code">assign</code> or <code class="inline-code">local</code> directive.
+ For example:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><#assign capturedOutput><@outputSomething /></#assign>
+<@otherDirective someParam=capturedOutput /></pre></div>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_questionmark">
+ 19.
+ Why do I have "?"-s in the output instead of
+ character <em>X</em>?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>This is because the character that you want to print can't
+ be represented with the <a href="gloss.html#gloss.charset">charset</a> (encoding) used for the
+ output stream, so the Java platform (not FreeMarker) substitutes
+ the problematic character with question mark. In general you
+ should use the same charset for the output as for the template
+ (use the <code class="inline-code">getEncoding()</code> method of the template
+ object), or which is even safer, you should always use UTF-8
+ charset for the output. The charset used for the output stream is
+ not decided by FreeMarker, but by you, when you create the
+ <code class="inline-code">Writer</code> that you pass to the
+ <code class="inline-code">process</code> method of the template.</p>
+
+ <p>Example: Here I use UTF-8 charset in a servlet:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-unspecified">...
+resp.setContentType("text/html; charset=utf-8");
+Writer out = resp.getWriter();
+...
+t.process(root, out);
+...</pre></div>
+
+ <p>Note that the question marks (or other substitution
+ characters) may be produced outside FreeMarker, in which case the
+ above obviously will not help. For example a bad/missconfigured
+ database connection or JDBC driver may bring the text already with
+ substitution characters in it. HTML forms are another potential
+ source of encoding problems. It's a good idea to print the
+ numerical code of the characters of the string on various places,
+ to see where the problem occurs first.</p>
+
+ <p>You can read more about charsets and FreeMarker <a href="pgui_misc_charset.html">here...</a></p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_retrieve_calculated_values">
+ 20.
+ How to retrieve values calculated in templates after
+ template execution done?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>First of all, be sure your application is designed well:
+ templates should display data, and almost never calculate data. If
+ you are still sure you want to do it, read on...</p>
+
+ <p>When you use <code class="inline-code"><#assign x = "foo"></code>,
+ then you do not actually modify the data-model (since that is
+ read-only, see: <a href="pgui_misc_multithreading.html">Programmer's Guide/Miscellaneous/Multithreading</a>), but
+ create the <code class="inline-code">x</code> variable in the runtime <a href="gloss.html#gloss.environment">environment</a> of the processing
+ (see <a href="pgui_misc_var.html">Programmer's Guide/Miscellaneous/Variables, scopes</a>). The problem is that this
+ runtime environment will be discarded when
+ <code class="inline-code">Template.process</code> returns, as it was created for
+ a single <code class="inline-code">Template.process</code> call:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-unspecified">// internally an Environment will be created, and then discarded
+myTemplate.process(root, out);</pre></div>
+
+ <p>To prevent this, you can do the below, which is equivalent
+ with the above, except that you have chance to return the
+ variables created in the template:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-unspecified">Environment env = myTemplate.createProcessingEnvironment(root, out);
+env.process(); // process the template
+TemplateModel x = env.getVariable("x"); // get variable x</pre></div>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_assign_to_dynamic_variable_name">
+ 21.
+ How to assign to (or <code class="inline-code">#import</code> into) a
+ dynamically constructed variable name (like to name that's stored
+ in another variable)?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>If you really can't avoid doing that (you should, as it's
+ confusing), you can solve that with constructing the appropriate
+ FTL source code dynamically in a string, then using the <a href="ref_builtins_expert.html#ref_builtin_interpret"><code>interpret</code>
+ built-in</a>. For example, if you want to assign to the
+ variable whose name is stored in the <code class="inline-code">varName</code>
+ variable:</p>
+
+
+
+<div class="code-wrapper"><pre class="code-block code-template"><@"<#assign ${varName}='example'>"?interpret /></pre></div>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_template_uploading_security">
+ 22.
+
+
+ Can I allow users to upload templates and what are the
+ security implications?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>In general you shouldn't allow that, unless those users are
+ system administrators or other trusted personnel. Consider
+ templates as part of the source code just like
+ <code class="inline-code">*.java</code> files are. If you still want to allow
+ users to upload templates, here are what to consider:</p>
+
+ <ul>
+ <li>
+ <p>Denial-of-Service (DoS) attacks: It's trivial to create
+ templates that run practically forever (with a loop), or
+ exhaust memory (by concatenating to a string in a loop).
+ FreeMarker can't enforce CPU or memory usage limits, so this
+ is something that has no solution on the
+ FreeMarker-level.</p>
+ </li>
+
+ <li>
+ <p>Data-model and wrapping
+ (<code class="inline-code">Configuration.setObjectWrapper</code>): The
+ data-model might gives access to the public Java API of some
+ objects that you have put into the data-model. By default, for
+ objects that aren't instances of a the bunch of specially
+ handler types (<code class="inline-code">String</code>,
+ <code class="inline-code">Number</code>, <code class="inline-code">Boolean</code>,
+ <code class="inline-code">Date</code>, <code class="inline-code">Map</code>,
+ <code class="inline-code">List</code>, array, and a few others), their
+ public Java API will be exposed. To avoid that, you have to
+ construct the data-model so that it only exposes the things
+ that are really necessary for the template. For that, you may
+ want to use <code class="inline-code">SimpleObjectWrapper</code> (via
+ <code class="inline-code">Configuration.setObjectWrapper</code> or the
+ <code class="inline-code">object_wrapper</code> setting) and then create the
+ data-model purely from <code class="inline-code">Map</code>-s,
+ <code class="inline-code">List</code>-s, <code class="inline-code">Array</code>-s,
+ <code class="inline-code">String</code>-s, <code class="inline-code">Number</code>-s,
+ <code class="inline-code">Boolean</code>-s and <code class="inline-code">Date</code>-s.
+ Or, you can implement your own extremely restrictive
+ <code class="inline-code">ObjectWrapper</code>, which for example could
+ expose your POJO-s safely.</p>
+ </li>
+
+ <li>
+ <p>Template-loader
+ (<code class="inline-code">Configuration.setTemplateLoader</code>):
+ Templates may load other templates by name (by path), like
+ <code class="inline-code"><#include "../secret.txt"></code>. To avoid
+ loading sensitive data, you have to use a
+ <code class="inline-code">TemplateLoader</code> that double-checks that the
+ file to load is something that should be exposed. FreeMarker
+ tries to prevent the loading of files outside the template
+ root directory regardless of template loader, but depending on
+ the underlying storage mechanism, exploits may exist that
+ FreeMarker can't consider (like, just as an example,
+ <code class="inline-code">~</code> jumps to the current user's home
+ directory). Note that
+ <code class="inline-code">freemarker.cache.FileTemplateLoader</code> checks
+ the canonical paths, so that's maybe a good candidate for this
+ task, yet, adding a file extension check (file must be
+ <code class="inline-code">*.ftl</code>) is maybe a good idea.</p>
+ </li>
+
+ <li>
+ <p>The <code class="inline-code">new</code> built-in
+ (<code class="inline-code">Configuration.setNewBuiltinClassResolver</code>,
+ <code class="inline-code">Environment.setNewBuiltinClassResolver</code>):
+ It's used in templates like
+ <code class="inline-code">"com.example.SomeClass"?new()</code>, and is
+ important for FTL libraries that are partially implemented in
+ Java, but shouldn't be needed in normal templates. While
+ <code class="inline-code">new</code> will not instantiate classes that are
+ not <code class="inline-code">TemplateModel</code>-s, FreeMarker contains a
+ <code class="inline-code">TemplateModel</code> class that can be used to
+ create arbitrary Java objects. Other "dangerous"
+ <code class="inline-code">TemplateModel</code>-s can exist in you
+ class-path. Plus, even if a class doesn't implement
+ <code class="inline-code">TemplateModel</code>, its static initialization
+ will be run. To avoid these, you should use a
+ <code class="inline-code">TemplateClassResolver</code> that restricts the
+ accessible classes (possibly based on which template asks for
+ them), such as
+ <code class="inline-code">TemplateClassResolver.ALLOWS_NOTHING_RESOLVER</code>.</p>
+ </li>
+ </ul>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_implement_function_or_macro_in_java">
+ 23.
+ How to implement a function or macro in Java Language
+ instead of in the template language?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>It's not possible (yet), but something very similar is
+ possible if you write a class that implements
+ <code class="inline-code">freemarker.template.TemplateMethodModelEx</code> or
+ <code class="inline-code">freemarker.template.TemplateDirectiveModel</code>
+ respectively, and then where you were write <code class="inline-code"><#function
+ my
+ <em class="code-color">...</em>><em class="code-color">...</em></#function></code>
+ or <code class="inline-code"><#macro my
+ <em class="code-color">...</em>><em class="code-color">...</em></#macro></code>
+ you write <code class="inline-code"><#assign my = "your.package.YourClass
+ "?</code><a href="ref_builtins_expert.html#ref_builtin_new"><code>new</code></a><code class="inline-code">()></code>
+ instead. Note that using the <code class="inline-code">assign</code> directive
+ for this works because functions (and methods) and macros are just
+ plain variables in FreeMarker. (For the same reason you could also
+ put <code class="inline-code">TemplateMethodModelEx</code> or
+ <code class="inline-code">TemplateDirectiveModel</code> instances into the
+ data-model before calling the template, or into the shared
+ variable map (see:
+ <code class="inline-code">freemarker.template.Configuration.setSharedVariable(String,
+ TemplateModel)</code>) when you initialize the
+ application.)</p>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_nice_error_page">
+ 24.
+ <a name="misc.faq.niceErrorPage"></a> In my Servlet
+ based application, how do I show a nice error page instead of a
+ stack trace when error occurs during template processing?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>First of all, use <code class="inline-code">RETHROW_HANDLER</code> instead
+ of the default <code class="inline-code">DEBUG_HANDLER</code> (for more
+ information about template exception handlers <a href="pgui_config_errorhandling.html">read this...</a>). Now
+ FreeMarker will not print anything to the output when an error
+ occurs, so the control is in your hands. After you have caught the
+ exception of
+ <code class="inline-code">Template.process(<em class="code-color">...</em>)</code>
+ basically you can follow two strategies:</p>
+
+ <ul>
+ <li>
+ <p>Call <code class="inline-code">httpResp.isCommitted()</code>, and if
+ that returns <code class="inline-code">false</code>, then you call
+ <code class="inline-code">httpResp.reset()</code> and print a "nice
+ error page" for the visitor. If the return value was
+ <code class="inline-code">true</code>, then try to finish the page be
+ printing something that makes clear for the visitor that the
+ page generation was abruptly interrupted because of an error
+ on the Web server. You may have to print a lot of redundant
+ HTML end-tags and set colors and font size to ensure that the
+ error message will be actually readable in the browser window
+ (check the source code of the
+ <code class="inline-code">HTML_DEBUG_HANDLER</code> in
+ <code class="inline-code">src\freemarker\template\TemplateException.java</code>
+ to see an example).</p>
+ </li>
+
+ <li>
+ <p>Use full page buffering. This means that the
+ <code class="inline-code">Writer</code> doesn't send the output to the
+ client progressively, but buffers the whole page in the
+ memory. Since you provide the <code class="inline-code">Writer</code>
+ instance for the
+ <code class="inline-code">Template.process(<em class="code-color">...</em>)</code>
+ method, this is your responsibility, FreeMarker has nothing to
+ do with it. For example, you may use a
+ <code class="inline-code">StringWriter</code>, and if
+ <code class="inline-code">Template.process(<em class="code-color">...</em>)</code>
+ returns by throwing an exception, then ignore the content
+ accumulated by the <code class="inline-code">StringWriter</code>, and send
+ an error page instead, otherwise you print the content of
+ <code class="inline-code">StringWriter</code> to the output. With this
+ method you surely don't have to deal with partially sent
+ pages, but it can have negative performance implications
+ depending on the characteristic of the pages (for example, the
+ user will experience more response delay for a long page that
+ is generated slowly, also the server will consume more RAM).
+ Note that using a <code class="inline-code">StringWriter</code> is surely
+ not the most efficient solution, as it often reallocates its
+ buffer as the accumulated content grows.</p>
+ </li>
+ </ul>
+ </dd>
+
+
+
+
+
+ <dt class="question" id="faq_html_editor_mangles">
+ 25.
+ I'm using a visual HTML editor that mangles template tags.
+ Will you change the template language syntax to accommodate my
+ editor?
+
+ </dt>
+
+
+ <dd class="answer">
+
+ <p>We won't change the standard version, because a lot of
+ templates depend on it.</p>
+
+ <p>Our view is that the editors that break template code are
+ themselves broken. A good editor should ignore, not mangle, what
+ it doesn't understand.</p>
+
+ <p>You maybe interested in that starting from FreeMarker 2.3.4
+ you can use <code class="inline-code">[</code> and <code class="inline-code">]</code> instead
+ of <code class="inline-code"><</code> and <code class="inline-code">></code>. For more
+ details <a href="dgui_misc_alternativesyntax.html">read
+ this...</a></p>
+ </dd>
+
+
+ </dl>
+
+ </div>
+<div class="bottom-pagers-wrapper"><div class="pagers bottom"><a class="paging-arrow previous" href="app.html"><span>Previous</span></a><a class="paging-arrow next" href="app_versions.html"><span>Next</span></a></div></div></div></div> </div>
+ </div>
+<div class="site-footer"><div class="site-width"><div class="footer-top"><div class="col-left sitemap"><div class="column"><h3 class="column-header">Overview</h3><ul><li><a href="http://freemarker.org/">What is FreeMarker?</a></li><li><a href="http://freemarker.org/freemarkerdownload.html">Download</a></li><li><a href="app_versions.html">Version history</a></li><li><a href="http://freemarker.org/history.html">About us</a></li><li><a itemprop="license" href="app_license.html">License</a></li></ul></div><div class="column"><h3 class="column-header">Handy stuff</h3><ul><li><a href="http://freemarker-online.kenshoo.com/">Try template online</a></li><li><a href="dgui_template_exp.html#exp_cheatsheet">Expressions cheatsheet</a></li><li><a href="ref_directive_alphaidx.html">#directives</a></li><li><a href="ref_builtins_alphaidx.html">?built_ins</a></li><li><a href="ref_specvar.html">.special_vars</a></li></ul></div><div class="column"><h3 class="column-header">Community</h3><ul><li><a href
="https://github.com/freemarker/freemarker">FreeMarker on Github</a></li><li><a href="https://twitter.com/freemarker">Follow us on Twitter</a></li><li><a href="https://issues.apache.org/jira/browse/FREEMARKER/">Report a bug</a></li><li><a href="http://stackoverflow.com/questions/ask?tags=freemarker">Ask a question</a></li><li><a href="http://freemarker.org/mailing-lists.html">Mailing lists</a></li></ul></div></div><div class="col-right"><ul class="social-icons"><li><a class="github" href="https://github.com/freemarker/freemarker">Github</a></li><li><a class="twitter" href="https://twitter.com/freemarker">Twitter</a></li><li><a class="stack-overflow" href="http://stackoverflow.com/questions/ask?tags=freemarker">Stack Overflow</a></li></ul><a class="xxe" href="http://www.xmlmind.com/xmleditor/" rel="nofollow" title="Edited with XMLMind XML Editor"><span>Edited with XMLMind XML Editor</span></a></div></div><div class="footer-bottom"> <p class="last-generated">
+Last generated:
+<time itemprop="dateModified" datetime="2017-03-13T10:55:28Z" title="Monday, March 13, 2017 10:55:28 AM GMT">2017-03-13 10:55:28 GMT</time>, for Freemarker 2.3.26 </p>
+<p class="copyright">
+� <span itemprop="copyrightYear">1999</span>\u20132017
+<a itemtype="http://schema.org/Organization" itemprop="copyrightHolder" hr
<TRUNCATED>