| <!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 - 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="FreeMarker Manual"> |
| <meta property="og:title" content="FAQ"> |
| <meta property="og:locale" content="en_US"> |
| <meta property="og:url" content="http://example.com/app_faq.html"> |
| <link rel="canonical" href="http://example.com/app_faq.html"> |
| <link rel="icon" href="favicon.png" type="image/png"> |
| <link rel="stylesheet" type="text/css" href="docgen-resources/docgen.min.css?1594338519184"> |
| </head> |
| <body itemscope itemtype="https://schema.org/Code"> |
| <meta itemprop="url" content="http://example.com/"> |
| <meta itemprop="name" content="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://example.com" role="banner"> <img itemprop="image" src="logo.png" alt="My Logo"> |
| </a></div></div><div class="header-bottom-bg"><div class="site-width search-row"><a href="index.html" class="navigation-header">FreeMarker Manual</a><div class="navigation-header"></div></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">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 class="sr-only">Bookmarks:</span><ul class="bookmark-list"><li><a href="alphaidx.html">Index</a></li><li><a href="gloss.html">Glossary</a></li><li><a href="ref.html">Reference</a></li><li>FAQ</li><li><a href="preface.html#test_target">Bőregér</a></li><li><a href="api/index.html">API</a></li><li><a href="../index.html">Home</a></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 = ["FreeMarker Manual","Appendixes","FAQ"];</script> |
| <script src="toc.js?1594338519184"></script> |
| <script src="docgen-resources/main.min.js?1594338519184"></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_install.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_jsp_vs_velocity"> |
| |
| Velocity 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_question_4"> |
| |
| 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_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_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 (macro) names that contain space, |
| dash or other special characters? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_11"> |
| |
| 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_question_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? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_14"> |
| |
| 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_question_18"> |
| |
| How can I use the output of a directive (macro) in |
| expressions (as a parameter to another directive)? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_19"> |
| |
| Why do I have ``?''-s in the output instead of character |
| <em>X</em>? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_20"> |
| |
| How to retrieve values calculated in templates after |
| template execution done? |
| </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_question_22"> |
| |
| Why is FreeMarker logging suppressed for my |
| application? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_23"> |
| |
| 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_question_24"> |
| |
| I'm using a visual HTML editor that mangles template tags. |
| Will you change the template language syntax to accommodate my |
| editor? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_25"> |
| |
| How fast is FreeMarker? Is it true that 2.x is slower than |
| 1.x (FreeMarker classic)? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_26"> |
| |
| How can my Java classes ask a template for information about |
| its structure (e.g. a list of all the variables)? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_27"> |
| |
| Will you ever provide backward compatibility? |
| </a> |
| </li> |
| <li> |
| <a href="#faq_question_28"> |
| |
| If we distribute FreeMarker with our product, do we have to |
| release the source code for our product? |
| </a> |
| </li> |
| </ol> |
| <dl> |
| |
| |
| |
| <dt class="question" id="faq_jsp_vs_freemarker"> |
| 1. |
| JSP versus FreeMarker? |
| |
| |
| |
| </dt> |
| |
| |
| <dd class="answer"> |
| |
| <p>Note: JSP 1.x was really bad as an MVC template engine |
| because it was not made for that, so I don't deal with that here. |
| We compare FreeMarker with the JSP 2.0 + JSTL combo.</p> |
| |
| <p>FreeMarker Pros:</p> |
| |
| <ul> |
| <li> |
| <p>FreeMarker is not tied to Servlets, networking or the |
| 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>No servlet specific scopes and other highly technical |
| things in templates. 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. |
| Since we mostly 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>. |
| You can easily switch this behavior and output non-localized |
| numbers by default.</p> |
| </li> |
| |
| <li> |
| <p>Easier to define ad-hoc macros and functions.</p> |
| </li> |
| |
| <li> |
| <p>No sweeping errors under the carpet. Missing variables |
| will cause an error by default, and not silently default to |
| arbitrary values. Also, <code class="inline-code">null</code>-s are not |
| treated silently as 0/false/empty string. <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 (compare it to |
| how JSP custom tags work), so they can be easily passed around |
| as parameter values, put into the data-model, ...etc, just |
| like any other value.</p> |
| </li> |
| |
| <li> |
| <p>Easier to read, more terse syntax. For example: |
| <code class="inline-code"><#if x>...</#if></code> instead of |
| <code class="inline-code"><c:if |
| test="${x}">...</c:if></code></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, JSP tag libraries work |
| without modification in FreeMarker templates, if they are not |
| using <code class="inline-code">.tag</code> files.)</p> |
| </li> |
| |
| <li> |
| <p>Since macros and function are just variables, incorrect |
| directive and parameter names and missing required parameters |
| can be detected only on runtime.</p> |
| </li> |
| |
| <li> |
| <p>Its syntax doesn't follow the HTML/XML rules appart from |
| some visual similarity, which is confusing for new users. |
| (It's the price of the terseness...)</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: <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_jsp_vs_velocity"> |
| 2. |
| Velocity versus FreeMarker? |
| |
| |
| |
| </dt> |
| |
| |
| <dd class="answer"> |
| |
| <p><a href="http://jakarta.apache.org/velocity/index.html">Velocity</a> |
| is a simpler, more lightweight tool. Thus, it does not address |
| many tasks that FreeMarker does, and its template language is less |
| powerful in general, but it is simpler; visit <a href="http://freemarker.org/fmVsVel.html">http://freemarker.org/fmVsVel.html</a> |
| for details. Currently (2005) Velocity has wider third party |
| support and larger user community.</p> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id="faq_picky_about_missing_vars"> |
| 3. |
| 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 hiders 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, |
| or for which the programmer uses a different name. Human is |
| prone to do such accidental mistakes, 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 |
| hasDetp><em class="code-color">print dept |
| here...</em></#if></code>, which would then |
| silently never print the dept of the visitor, since you have |
| mistyped the variable name (it should be |
| <code class="inline-code">hasDept</code>). Also think about maintenance, |
| when you later modify your application... most probably you |
| will not re-check templates that carefully each time.</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 it don't know to be |
| 0/false, it is a quite irresponsible and arbitrary thing. Just |
| because it is not know what's your current bank account |
| balance, can we just say it is $0 (and how easy it is to |
| accidentally write <code class="inline-code">Balance: ${balanace}</code>)? |
| Just because it is not known if a patient has penicillin |
| allergy, we can just say he/she doesn't have (and how easy it |
| is to accidentally write <code class="inline-code"><#if |
| hasPenicilinAllergy><em class="code-color">Warning...</em><#else><em class="code-color">Allow...</em></#if></code>; |
| there is a typo in this, if you didn't see)? Just consider the |
| implications of such mistakes for a moment. They can be quite |
| severe and troubling. Showing an error page is often better |
| than showing incorrect information that formally looks |
| good.</p> |
| </li> |
| </ul> |
| |
| <p>Being not picky is mostly sweeping under the carpet in this |
| case (not facing with 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 in 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 with 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 is not |
| just results in awkward verbose templates, but increases the |
| probability of hiding errors and printing arbitrary incorrect |
| output (for the reasons described earlier).</p> |
| </li> |
| |
| <li> |
| <p>On a production server 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 other error |
| handler</a> than the default. Error handlers can be made |
| that rather skip the problematic part than abort 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. (Another feature you may interested in: |
| <a href="ref_directive_attempt.html">the |
| <code>attempt</code>/<code>recover</code> |
| directives</a>)</p> |
| </li> |
| </ul> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 4. |
| 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 |
| usable FreeMarker release. You may use an older release.</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 (such as in the Ant <code class="inline-code">lib</code> directory), |
| which has higher priority. 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 release before 2.3-final or 2.2.8, but you can |
| still try to get the version number in the Java code of your |
| application with |
| <code class="inline-code">Configuration.getVersionNumber()</code>. If this |
| method is not present either, then you are using an early |
| 2.3-preview, or a version before 2.2.6.</p> |
| |
| <p>If you think that the documentation or FreeMarker is wrong, |
| please report it using the bug tracker, or the mailing list, or |
| the forums on <a href="http://sourceforge.net/projects/freemarker/">http://sourceforge.net/projects/freemarker/</a>. |
| Thank you!</p> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id="faq_number_grouping"> |
| 5. |
| 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 unwanted formatting. To |
| prevent this, 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'' that 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> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id="faq_number_decimal_point"> |
| 6. |
| 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"> |
| 7. |
| 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. However, for generating source code |
| <code class="inline-code">${washable?string("true", "false")}</code> would be |
| very often used, so <code class="inline-code">${washable?string}</code> (i.e., |
| omitting the parameter list) is equivalent with that.</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 bid 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 (macro) names that contain space, |
| dash or other special characters? |
| |
| </dt> |
| |
| |
| <dd class="answer"> |
| |
| <p>If you have a variable with strange name, such as |
| <code class="inline-code">foo-bar</code>, FreeMarker will misinterpret what do |
| you want when you write thing as <code class="inline-code">${foo-bar}</code>. In |
| this concrete case, it will believe that you want 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 clean that these are just |
| syntactical problems. FreeMarker has no limitations regarding the |
| characters used in variable names, nor regarding the length of the |
| variable names, but sometimes you need to use syntactical |
| tricks.</p> |
| |
| <p>If you want to read the variable: Use the square bracket |
| syntax. An example of square bracket syntax is |
| <code class="inline-code">baaz["foo"]</code>, which is equivalent with |
| <code class="inline-code">baaz.foo</code>. As the subvariable name with the |
| square bracket syntax is a string literal (in fact, arbitrary |
| expression), it let you write <code class="inline-code">baaz["foo-bar"]</code>. |
| Now you may say that it can be used for hash subvariables only. |
| Yes, but top-level variables are accessible through special hash |
| variable <code class="inline-code">.vars</code>. For example, |
| <code class="inline-code">foo</code> is equivalent with |
| <code class="inline-code">.vars["foo"]</code>. So you can also write |
| <code class="inline-code">.vars["foo-bar"]</code>. Naturally, this trick works |
| with macro invocations too: |
| <code class="inline-code"><@.vars["foo-bar"]/></code></p> |
| |
| <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 |
| "foo-bar" = 1></code> and <code class="inline-code"><#macro |
| "foo-bar"></code>.</p> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 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>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=""> |
| 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 |
| apparently transforming the data-model to something that |
| serves the purpose of the presentation layer, and these |
| methods are part of the presentation layer.</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 <code class="inline-code">DefaultObjectWrapper</code> or the |
| <a href="pgui_misc_beanwrapper.html"><code>BeansWrapper</code></a> |
| then this will happen automatically (but be sure you are using |
| at least FreeMarker 2.3.3). Furthermore if you use |
| <code class="inline-code">BeansWrapper</code>, then the method will surely |
| get exactly the same instance that was earlier wrapped (as far |
| as it was wrapped by the |
| <code class="inline-code">BeansWrapper</code>).</p> |
| </li> |
| </ul> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 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 subvariables (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>So FTL's hashes are not general purpose associate arrays |
| that could be used for looking up values with keys of arbitrary |
| type. FTL is presentation oriented language, and it has no feature |
| dedicated for that purpose. It has, however, methods. Methods are |
| part of the data-model, and they can do all kind of fancy |
| data-model related calculations, so of course you can add some |
| methods to the data-model for <code class="inline-code">Map</code> lookup. The |
| bad news is that the building of the data-model, as it's an |
| application specific issue, is the task of the programmers who use |
| FreeMarker, so it's their task to ensure that such methods are |
| present there to serve the template authors. (However, when |
| template authors need to call methods that are not about |
| presentation, then consider if the data-model is simple enough. |
| Maybe you should push some calculations back to the data-model |
| building phase. Ideally the data-model contains what should be |
| displayed, and not something that serves as the base of further |
| calculations.)</p> |
| |
| <p>If you read the programmer's guide, then you know that |
| technically, the data-model is a tree of |
| <code class="inline-code">freemarker.template.TemplateModel</code> objects. The |
| building of the data-model usually (but not necessary) happens by |
| automatically wrapping (enclosing) plain Java objects into |
| <code class="inline-code">TemplateModel</code> objects. The object that does |
| this wrapping is the object wrapper, and it's specified when you |
| configure FreeMarker. FreeMarker comes with a few object wrapper |
| implementations out-of-the-box, and probably the most widely used |
| of them is <a href="pgui_misc_beanwrapper.html"><code>freemarker.ext.beans.BeansWrapper</code></a>. |
| If you use an instance of this as the object wrapper, then |
| <code class="inline-code">java.util.Map</code>-s you put into the data-model |
| will also act as a method, so you can write |
| <code class="inline-code">myMap(myKey)</code> in the template, that will |
| internally call <code class="inline-code">Map.get(myKey)</code>. There will be |
| no restriction regarding the type of <code class="inline-code">myKey</code>, as |
| <code class="inline-code">Map.get(Object key)</code> has no such restriction. If |
| the value of <code class="inline-code">myKey</code> was wrapped with |
| <code class="inline-code">BeansWrapper</code> or other object wrapper whose |
| wrapped objects support unwrapping, or it is given as literal in |
| the template, then the value will be automatically unwrapped to |
| plain Java object before the actual invocation of the |
| <code class="inline-code">Map.get(Object key)</code> method, so it will not be |
| invoked with <code class="inline-code">TemplateModel</code>-s.</p> |
| |
| <p>But there still will be a problem. Java's |
| <code class="inline-code">Map</code> is particular about the exact class of the |
| key, so 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 have to write |
| <code class="inline-code">${myMap.get(123?int)}</code>. This is an ugly effect |
| caused by that FTL's deliberately simplified type system just has |
| a single numerical type, while Java distinguishes a lot of |
| numerical types. (Ideally, in the above case, the programmers |
| ensure that the <code class="inline-code">get</code> method automatically |
| converts the key to <code class="inline-code">Integer</code>, so it's not the |
| problem of the template author. This can be done with wrapper |
| customization, but the wrapper has to know that the particular |
| <code class="inline-code">Map</code> object uses <code class="inline-code">Integer</code> |
| keys, which assumes application specific knowledge.) 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 |
| caluclations 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 <code class="inline-code">BeansWrapper</code> as |
| your object wrapper, 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>. Unfortunatelly, it's the default (for |
| backward compatibility), so you have to explicitly set it to |
| <code class="inline-code">true</code> where you create the object |
| wrapper.</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 subseqent |
| 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 two solutions, but |
| please read the warning after them:</p> |
| |
| <ul> |
| <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 <code class="inline-code"><@myList.append foo |
| /></code>). (Also, if you use |
| <code class="inline-code">BeansWrapper</code> and configure it so it exposes |
| the public methods, you can use the Java API for variables |
| that are for <code class="inline-code">java.util.Map</code>-s and |
| <code class="inline-code">java.util.List-s</code>. Just like with Apache |
| Velocity.)</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 |
| varaible exists with ``nullArg'' name.</p> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 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=""> |
| 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=""> |
| 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</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_implement_function_or_macro_in_java"> |
| 21. |
| 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=""> |
| 22. |
| Why is FreeMarker logging suppressed for my |
| application? |
| |
| </dt> |
| |
| |
| <dd class="answer"> |
| |
| <p>It is because FreeMarker does not find any logging system. |
| To fix this, you must make available one of the following logging |
| systems for your application: Avalon |
| (<code class="inline-code">org.apache.log</code>), Log4J |
| (<code class="inline-code">org.apache.log4j</code>), or use J2SE 1.4 or later |
| (that contains <code class="inline-code">java.util.logging</code>). That is, the |
| class-loader used with your application must find one of the |
| mentioned classes.</p> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 23. |
| <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=""> |
| 24. |
| 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> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 25. |
| How fast is FreeMarker? Is it true that 2.x is slower than |
| 1.x (FreeMarker classic)? |
| |
| </dt> |
| |
| |
| <dd class="answer"> |
| |
| <p>First of all, don't forget that FreeMarker is only the view |
| rendering component in an <a href="gloss.html#gloss.MVC">MVC</a> |
| system. Furthermore MVC templates tend to be simple: many static |
| text with a few interpolations and loops and conditional block. So |
| it is not like PHP or Model 1 JSP; your application performance is |
| not affected that much by the execution time of templates.</p> |
| |
| <p>FreeMarker is certainly fast enough that it will only very |
| rarely be a bottleneck in your application. Rather, other factors |
| such as the speed of the data-base operations or network bandwidth |
| will likely dominate. The impact of FreeMarker performance could |
| be noticeable only for really busy sites (say, over 30 hits per |
| second per server), where almost all database data is cached. If |
| you are finding FreeMarker slow, do make sure that the cache of |
| parsed templates works well |
| (<code class="inline-code">Configuration.getTemplate</code> be default uses |
| caching). Parsing a template file is a relatively costly step; in |
| most long-running server-side applications, you will want to parse |
| a template once and have it be used many times. (Note that |
| FreeMarker 2.1.4 and earlier versions have bugs that sometimes can |
| ruin caching.)</p> |
| |
| <p>FreeMarker 2.1 is slower than 1.7.1. This surely depends on |
| your templates, but it could be slower by a factor of 2 or 3. But |
| again, it does not means that response time will be 2 or 3 times |
| slower; most FreeMarker user simply should not be able to perceive |
| the change in the final response time.</p> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 26. |
| How can my Java classes ask a template for information about |
| its structure (e.g. a list of all the variables)? |
| |
| </dt> |
| |
| |
| <dd class="answer"> |
| |
| <p>In FreeMarker 2.2, <code class="inline-code">Template</code> has an |
| undocumented method for examining the parsed template: |
| <code class="inline-code">getRootTreeNode</code>.</p> |
| |
| <p>But listing all accessed variables is not possible, because |
| variable names can be dynamically generated from data. However, |
| there's a more important reason why FreeMarker doesn't support |
| this. The design of FreeMarker is based on the idea of a |
| separation between business objects and presentation objects. This |
| separation takes two forms:</p> |
| |
| <div class="orderedlist"><ol type="1"> |
| <li> |
| <p>The templates know what data to expect, but they don't |
| know how it's generated.</p> |
| </li> |
| |
| <li> |
| <p>The business objects know what data to produce, but they |
| don't know how it's going to be displayed. Therefore, they |
| don't know anything about templates.</p> |
| </li> |
| </ol></div> |
| |
| <p>Since the business objects don't rely on the templates, if |
| you need to use them with some other presentation system, you |
| won't have to rewrite your application.</p> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 27. |
| Will you ever provide backward compatibility? |
| |
| </dt> |
| |
| |
| <dd class="answer"> |
| |
| <p>FreeMarker 2.0 was a complete rewrite of FreeMarker 1.x, by |
| a new author. The 1.x series continues as separated project: |
| FreeMarker Classic. Since 2.x follows different philosophy than |
| 1.x, 2.0x releases were immature despite the high major version |
| number. This caused further radical changes between 2.01 and 2.1. |
| As of 2.1 things were much more matured, and 2.2 is almost |
| backward compatible with 2.1. We hope that this tendency |
| continues.</p> |
| |
| <p>Currently, the rule is that releases with different second |
| version number (as 2.1.x and 2.2.x) are not (fully) compatible. |
| Releases where only the third version number differs (as 2.2.1 and |
| 2.2.6) are compatible.</p> |
| |
| <p>We always provide backward compatible bugfix releases for |
| the released versions. So basically, you don't |
| <em>have</em> to switch to a new, non-backward |
| compatible release in an already written product. It's a something |
| for something situation... FreeMarker recovers faster from design |
| mistakes than many other projects, but the price of this is that |
| major releases are not backward compatible. This is admittedly not |
| optimal, it would be better if there are fewer design mistakes... |
| but, well, it is the reality.</p> |
| </dd> |
| |
| |
| |
| |
| |
| <dt class="question" id=""> |
| 28. |
| If we distribute FreeMarker with our product, do we have to |
| release the source code for our product? |
| |
| </dt> |
| |
| |
| <dd class="answer"> |
| |
| <p>No. As of 2.0, FreeMarker is released under a BSD-style |
| license. This means that source or binary distributions may be |
| made freely, and can be included in other products, whether |
| commercial or open source.</p> |
| |
| <p>The only restrictions apply to the copyright of FreeMarker |
| itself, and the use of FreeMarker or its contributors as |
| endorsements of your own product. See the <a href="app_license.html">LICENSE</a> for further details.</p> |
| |
| <p>If you use FreeMarker, we hope you'll send us a link to some |
| information about your product, but that's optional as |
| well.</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_install.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><div class="col-right"><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="2020-07-09T23:48:39Z" title="Thursday, July 9, 2020 11:48:39 PM GMT">2020-07-09 23:48:39 GMT</time> </p> |
| <p class="copyright"> |
| © <span itemprop="copyrightYear">1999</span>–2020 |
| <a itemtype="http://schema.org/Organization" itemprop="copyrightHolder" href="https://apache.org/">The Apache Software Foundation</a> </p> |
| </div></div></div></body> |
| </html> |