Apache FreeMarker is a template engine for generating any kind of text output from HTML to email, etc. Spring Framework has built-in integration for using Spring MVC with FreeMarker templates.

View Configuration

The following example shows how to configure FreeMarker as your presentation technology:

The following example shows how to configure the same in XML:

In addition, you can declare a FreeMarkerConfigurer bean for complete control over all properties, like shown in the following example:

Your templates should be stored in the directory specified by FreeMarkerConfigurer , as shown in the previous example. Given the previous configuration, if your controller returns the view name welcome , the resolver looks for the pattern /WEB-INF/freemarker/welcome.ftl .

FreeMarker Configuration

It is possible to pass the FreeMarker handler's "Settings" and "SharedVariable" directly to the FreeMarker handler's Configuration object (which is managed by Spring) by setting the appropriate bean properties in the FreeMarkerConfigurer . The freemarkerSettings property requires a java.util.Properties object, and the freemarkerVariables property requires a java.util.Map object. The following example shows how to use FreeMarkerConfigurer :

Details about the settings and variables that apply to the object Configuration , see FreeMarker documentation.

Form Handling

Spring provides a library of tags for use in JSP, which contains, among other things, the <spring:bind/> . This element primarily allows forms to display values from underlying form objects and display the results of failed validations from a Validator in the web or business tier. Spring also has support for the same functionality in FreeMarker, with additional convenience macros for generating the form input elements themselves.

Binding macros

The support for the standard set of macros is in the file spring-webmvc.jar for FreeMarker, so they are always available to a suitably configured application.

Some macros defined in Spring templating libraries are considered internal (private), but there is no such restriction in macro definitions , which makes all macros visible to calling code and user templates. The following sections cover only macros that need to be called directly from templates. If you need to view the macro code directly, the file is called spring.ftl and is located in the org.springframework.web.servlet.view.freemarker package.

Simple Binding

In your FreeMarker template-based HTML forms that act as the form view for a Spring MVC controller, you can use code like the following example to bind to field values and output to Error message screen for each input field is similar to the JSP equivalent. The following example shows the personForm view:

<@spring.bind> requires a "path" argument, which consists of the name of your command object (this is "command" unless you changed it in the controller configuration), followed by a dot and the name of the command object field you want to bind to. You can also use nested fields, such as command.address.street . The bind macro provides default HTML escape logic, specified by the defaultHtmlEscape parameter of the ServletContext context in web.xml.

An alternative form of the <@spring.bindEscaped> takes a second argument that explicitly specifies whether HTML escaping should be used in status detection error messages or values. You can set the value to true or false depending on your need. Additional form macros make HTML escaping easier to use, and you should use these macros whenever possible. These are described in the next section.

Input macros

Additional helper macros for FreeMarker simplify form binding and generation (including displaying validation errors). There is no need to use these macros to create form input fields; they can be mixed and matched using plain HTML or direct calls to the Spring binding macros we covered earlier.

The following table of available macros summarizes the FreeMarker Template definitions (FTL) and a list of parameters that each of them accepts:

The parameters of any of the above macros have a clear meaning:

path : name of the field to bind (i.e. "command.name")

options : Map of all available values that can be selected in the input field. Map keys are values that are passed back from the form and bound to the command object. The Map objects stored along with the keys are the labels that are displayed on the form to the user and may differ from the corresponding values returned by the form. Typically such a Map is provided by the controller as reference data. You can use any Map implementation depending on the required operating logic. For strictly sorted Maps, you can use a SortedMap (such as a TreeMap) with a suitable Comparator, and for arbitrary Maps that need to return values in insertion order, use a LinkedHashMap or a LinkedMap from commons-collections.

separator : If multiple options are available as separate elements (radio buttons or checkboxes), then this parameter represents the sequence of characters used to separate each of them in the list (for example, <br> ).

attributes : An additional string of arbitrary tags or text to include in the HTML tag itself. This line is repeated letter by the macro. For example, the textarea field can pass attributes (for example, 'rows="5" cols="60"') or style information, for example, 'style="border:1px solid silver"'.

classOrStyle : for the macro showErrors - the name of the CSS class that is used in the span element, wrapping each error. If no information is provided (or the value is empty), errors are wrapped in <b></b> tags.

The following sections provide examples of macros.

Input fields

The formInput macro accepts the parameter path(command.name ) and an additional parameter attributes (which is empty in the following example). This macro, like all other form generation macros, does an implicit Spring binding to the "path" parameter. The binding remains valid until a new binding is made, so the showErrors macro does not need to pass the path parameter again - it operates on the field for which the binding was last created.

The showErrors macro takes a separator parameter (characters that are used to separate multiple errors in a given field) and also takes a second parameter - this time a class name or style attribute. Note that FreeMarker can set default values for the "attributes" parameter. The following example shows how to use the formInput and showErrors macros:

The following example shows the output of a form fragment with generating a name field and displaying a validation error after how the form was submitted without a value in the field. Validation occurs through the Validation framework in Spring.

The generated HTML is similar to the following example:

The formTextarea macro works the same as the formInput macro, and accepts the same list of parameters. Typically the second parameter ( attributes ) is used to pass style information or the rows and cols attributes for the textarea .

Select Fields

You can use four select field macros to generate regular UI value selection inputs in your HTML forms :

formSingleSelect

formMultiSelect

formRadioButtons

formCheckboxes

Each of the four macros accepts a Map option, which contains a value for the form field and a label corresponding to that value. The value and label can be the same.

The following example concerns radio buttons in FTL. The underlying form object sets this field to a default value of "London", so no validation is required. When the form is displayed, the entire list of cities to select is provided as reference data in the model under the name "cityMap". The following listing shows an example:

The previous listing displays a row of radio buttons, one for each value in the cityMap , and uses the delimiter "" . No additional attributes are assigned (the last macro parameter is missing). cityMap uses the same String for each key-value pair in the Map. Map keys are what the form actually sends as parameters to the POST request. Map values are the labels that the user sees. In the previous example, given a list of three known cities and a default value in the base form object, the HTML looks like this:

If your The application assumes working with cities using internal codes (for example), then you can create a Map of codes with the corresponding keys, as shown in the following example:

The code now outputs data where the switch values are the corresponding codes, but the user still sees more user-friendly city names, as shown below:

HTML escaping

Using the default form macros described earlier results in HTML elements that conform to the HTML 4.01 standard and use the default HTML escaping value defined in your web.xml file, which is used by the Spring binding support tools. To make elements XHTML compliant, or to override the default HTML escaping value, you can set two variables in your template (or in your model, where your templates see them). The advantage of setting them in templates is that they can be changed to others values later in template processing to provide different logic for different fields in your form.

To switch to XHTML compliant mode for your tags, set the value to true for the model or context variable named xhtmlCompliant , as shown in the following example:

After processing this directive, all elements created by Spring macros will now be compliant with the XHTML standard.

Similarly, you can specify HTML escaping for each field, as shown in the following example:

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

FreeMarker

  • Report a Bug
  • Apache FreeMarker Manual
  • Template Language Reference
  • Built-in Reference

Seldom used and expert built-ins

  • Alpha. index
  • Expressions
  • #directives

absolute_template_name

Api, has_api, byte, double, float, int, long, short, has_content, markup_string, number_to_date, number_to_time, number_to_datetime, with_args_last.

These are the built-ins that normally you should not use, but in exceptional situations (debugging, advanced macros) they can be useful. If you need to use these in your normal page templates, you may revisit the data-model so you don't need to use these.

Converts a template name to an absolute name, which can be safely passed to <#include name > or <#import name as ns > or .get_optional_template( name ) and such in another template, as it won't be misinterpreted to be relative to the directory of the template that contains the include , import , etc. For example, if you are in template "dir/here.ftl" , then "target.ftl" is converted to "/dir/target.ftl" (note the initial / ). If now you pass this value to a template in "other-dir/there.ftl" , where it's passed to the include directive, then it won't be misinterpreted as "other-dir/target.ftl" , like "target.ftl" would have been.

Optionally, you can specify a root based name (a name that's either relative to the template root directory, or is absolute) that will be used instead of the name of the current template, like pathToConver ?absolute_template_name( otherTemplateName ) .

Example of an application (also uses .caller_template_name and .get_optional_template ):

These built-ins exists since FreeMarker 2.3.22

value ?api provides access to the API (usually, the Java API) of value , like value ?api. someJavaMethod() or value ?api. someBeanProperty , if the value itself supports exposing its API. This meant to be used rarely, when you need to call a Java method of an object, but the by-design simplistic view of the value that FreeMarker exposes to the templates hides that, and there's no equivalent built-in either. For example, when you put a Map into the data-model (and you are using the default object wrapper), myMap.myMethod() in a template basically translates to ((Method) myMap.get("myMethod")).invoke(...) in Java, thus you can't call myMethod . If, however, you write myMap?api.myMethod() instead, that means myMap.myMethod() in Java. Similarly, myMap?api.myProperty translates to myMap.getMyProperty() in Java, instead of to myMap.get("myProperty") .

You should avoid using api , and rely on the capabilities of the FTL types and the related built-ins as far as possible. For example, don't use users?api.size() , but users?size . The variation that uses ?api is more verbose, slower, more easily breaks when FreeMarker configuration settings are changed, and most importantly, more prone to break as the technical details of the data-model change. For example, if users is changed from a List to an array, users?size will keep working, while users?api.size() will break.

Avoid calling methods that modify an object (especially Map -s and Collection -s) or that aren't thread safe from other reasons. Templates usually aren't expected to modify the objects exposed to them, just to display them. Thus the application may passes some objects to multiple (possibly concurrent) template processings.

The api built-in is not everywhere available, some requirements has to be met:

The api_builtin_enabled configuration setting must be set to true . Its default is false (at least as of 2.3.22) for not lowering the security of existing applications.

The value itself has to support it. We are talking about the value as the template sees it, which is created from the original object (that's coming from the data-model or from a Java method return value) value via object wrapping . Hence, this depends on the object_wrapper FreeMarker configuration setting, and on the class of the wrapped (the original) object:

When the object wrapper is a DefaultObjectWrapper with its incompatibleImprovements set to 2.3.22 or higher ( see how to set it here ), FTL values made from Map -s and List -s support ?api . (Actually, what matters is that its useAdaptersForContainer property is set to true , but that's the default with said incompatibleImprovements .) Other java.util.Collections (such as Set -s) only support ?api if DefaultObjectWrapper 's forceLegacyNonListCollections property is set to false (the default is true for better out-of-the-box backward compatibility).

When wrapped with pure BeansWrapper , all values support ?api .

Custom TemplateModel -s can support ?api by implementing the freemarker.template.TemplateModelWithAPISupport interface.

Using ?api when it's not allowed in the configuration or when the value doesn't support it will abort template processing with error.

Whether a value supports ?api can be checked like value ?has_api , which returns a boolean value. Note that the result of ?has_api isn't influenced by the api_builtin_enabled setting.

Returns a SimpleNumber which contains the same value as the original variable, but uses java.lang. Type for the internal representation of the value. This is useful if a method is overloaded, or if a TemplateModel unwrapper has problem with automatically choosing the suitable java.lang.* type. Note that since version 2.3.9 the unwrapper has been improved substantially, so you will hardly ever need to use these built-ins to convert between numerical types, except for resolving ambiguity in overloaded method invocation.

The long built-in can also be used with date, time and date-time values to get the value as java.util.Date.getTime() would return. This is useful if you have to call a Java methods that expect a timestamp as a long .

This built-in evaluates a string as an FTL expression . For example "1+2"?eval returns the number 3. (To render a template that's stored in a string, use the interpret built-in instead.)

Do not use this to evaluate JSON! For that use the eval_json built-in instead. While FTL expression language looks similar to JSON, not all JSON is valid FTL expression. Also, FTL expressions can access variables, and call Java methods on them, so if you ?eval strings coming from untrusted source, it can become an attack vector.

The evaluated expression sees the same variables (such as locals) that are visible at the place of the invocation of eval . That is, it behaves similarly as if in place of s ?eval you had the value of s there. Except, it can't use loop variable built-ins that refer to a loop variable that was created outside s .

Regarding the configuration settings that affect the parsing (like syntax) and evaluation the rules are the same as with the interpret built-in .

This built-in is available since FreeMarker 2.3.31.

This built-in evaluates a string as a JSON expression , so that you can extract data from inside it. For example, if you receive data in the dataJson variable, but it's unfortunately just a flat string that contains {"name": "foo", "ids": [11, 22]} , then you can extract data from it like this:

Ideally, you shouldn't need eval_json , since the template should receive data already parsed (to List -s, Map -s, Java beans, etc.). This built-in is there as a workaround, if you can't improve the data-model.

The evaluated JSON expression doesn't have to be a JSON object (key-value pairs), it can be any kind of JSON value, like JSON array, JSON number, etc.

The syntax understood by this built-in is a superset of JSON:

Java-style comments are supported ( /* ... */ and // ... )

BOM (byte order mark) and non-breaking space ("nbsp") are treated as whitespace (in a stricter JSON parser they are errors of occurring around tokens).

No other non-JSON extras are implemented, notably, it's impossible to refer to variables (unlike in the eval built-in ). This is important for safety, when receiving JSON from untrusted sources.

It is true if the variable exists (and isn't Java null ) and is not "empty", otherwise it is false . The meaning of "empty" depends on the concrete case. This follows intuitive common-sense ideas. The following are empty: a string with 0 length, a markup output value with 0 length markup, a sequence or hash with no sub variables, a collection which has passed the last element. If the value is not of any of these types, then it counts as non-empty if it's a number or a date or a boolean (e.g. 0 and false are not empty), otherwise it counts as empty. Note that when your data-model implements multiple template model interfaces you may get unexpected results. However, when in doubt you can use always use expr!?size > 0 or expr!?length > 0 instead of expr?has_content .

This buit-in is exceptional in that you can use the parentheses trick like with the default value operator . That is, you can write both product.color?has_content and (product.color)?has_content . The first doesn't handle the case when product is missing, the last does.

This built-in parses a string as an FTL template, and returns an user-defined directive that executes that template, just as if a template with that content were include -d at that point. Example:

The output:

As you can see, inlineTemplate is a user-defined directive that, when executed, runs the template whose content is the value of templateSource .

The name of the template created by interpret is the name of the template that calls interpret , plus "->anonymous_interpreted" . For example, if the template that calls the built-in is "foo/bar.ftl" , then the name of the resulting template is "foo/bar.ftl->anonymous_interpreted" . Thus, relative paths inside the interpreted template are relative to this path (i.e., the base directory will be "foo" ), and errors inside the interpreted template will point to this generated template name.

For more helpful error messages, you can override the template name part after the "->" . For example, let's say mailTemplateSource comes from the mail_template database table, and in the case of error, you want the error log to contain the database ID of the failing template:

As you can see, interpret can be applied on a sequence of two items, in which case the first item is the FTL string to interpret, and the second items is the template name used after the "->" .

The configuration settings that affect the interpreted template are the same as of the surrounding template, except that parser settings specified in the ftl directive or was established via tag syntax or naming convention auto-detection are instead coming from the Configuration object (or naturally, from the TemplateConfiguration , if there's any). Thus the tag syntax, naming convention, whitespace handling, etc. of the interpreted template is independent of that established inside the surrounding template. An important exception from this rule is that the output format and auto-escaping policy is inherited from the lexical context where interpret is called from. For example in a template that has <#ftl output_format="XML"> header (or if you are inside a <#output_format "XML"> ... </#output_format> block), interpret calls in it will produce directives with XML output format.

These built-ins check the type of a variable, and returns true or false depending on the type. The list of is_ ... built-ins:

This built-in is available since FreeMarker 2.3.24.

Returns the markup stored inside a markup output value as string. This is useful if the value has to be passed to a Java method for a String parameter, or if we want to manipulate the markup directly in the template. Note that the resulting string can be converted back to markup output value with ?no_esc .

This built-in returns the namespace (i.e. the "gate" hash to the namespace) associated with a macro or function variable. You can use it with macros and functions only.

This is to create a variable of a certain TemplateModel implementation.

On the left side of ? you specify a string, the full-qualified class name of a TemplateModel implementation. The result is a method variable that calls the constructor, and returns the new variable.

For more information about how the constructor parameters are unwrapped and how overloaded constructor is chosen, read: Programmer's Guide/Miscellaneous/Bean wrapper

This built-in can be a security concern because the template author can create arbitrary Java objects and then use them, as far as they implement TemplateModel . Also the template author can trigger static initialization for classes that don't even implement TemplateModel . You can (since 2.3.17) restrict the classes accessible with this built-in using Configuration.setNewBuiltinClassResolver(TemplateClassResolver) or the new_builtin_class_resolver setting. See the Java API docs for more information. If you are allowing not-so-much-trusted users to upload templates then you should definitely look into this topic.

These are used to convert a number (usually a Java long ) to a date, time or date-time, respectively. This does them same as new java.util.Date(long) in Java, that is, the number is interpreted as the milliseconds passed since the epoch. The number can be anything and of any type as far as its value fits into a long . If the number isn't a whole number, it will be rounded to whole with half-up rule.

The output will be something like this (depending on the current locale and time zone):

This built-in is used to convert a listable value (one that you can iterate through with the list directive ) to a more capable sequence value. Sequences support operations like xs[index] and xs?size . Also, the resulting value is listable for multiple times, even if the original value was backed by a java.util.Iterator (which gives error when you try to list it for the 2nd time). This built-in is typically used to work around data-model problems, in case you can't fix the data-model itself. If you can, always fix the data-model instead (give a java.util.List or array to the template instead of a more restricted object, like a non- List java.util.Collection , or a java.util.Iterator ).

If the value is already a sequence, then this built-in just returns that as is. If the value is not something that the list directive could list, then template processing will be aborted with error. Otherwise, it usually fetches all the values, and stores them into a sequence. Be careful if you can have a huge number of items, as all of them will be held in memory on the same time. However, in some special cases fetching and/or storing all elements is avoided; see about the optimizations later.

You should convert a value with sequence only once. If you need the resulting sequence at multiple places, always assign the result to a variable, because if the value you convert is only listable once, converting it for the second time will result in error or an empty sequence. Also the conversion is somewhat costly for big collections, so it's better to do it only once.

Example: Let's say you find that users is only listable once (because it's a java.util.Iterator ), but you need to list it for multiple times in the template, and you can't fix the data-model. Then you could do this:

Optimizations

Since version 2.3.29, if the result of the sequence built-in is directly the input of to the [ index ] or [ range ] operator, or of ?size , or of ?first , or a chain of these operations, then the elements will not be collected into the memory, and only as many elements as strictly necessary will be fetched. For example anIterator?sequence[1] will just fetch the first 2 items (instead of building a sequence that contains all the elements, and then getting the 2nd element from that). Or, if you write anIterator?sequence?size , it will just skip through all elements to count them, but won't store them in memory.

The optimizations will only work within the same chain of built-in calls, so for example in <#assign seq = anIterator?sequence>${seq[1]} the ?sequence step will collect all the elements into the memory, as anIterator?sequence and seq[1] are separated. On the other hand, the optimizations will work in anIterator?sequence[10..]?size , as both [ range ] and ?size supports it, and they are directly chained together.

This built-in is available since 2.3.30

The goal of this built-in is to add parameters dynamically to the call of a directive (like a macro), function or method. Dynamically means that parameters are added based on a hash value (like {'a': 1, 'b': 2, 'c': 3} or a Java Map ), or a sequence value (like [1, 2, 3] or a Java List ), whose actual content is might only known at the moment when the call happens.

For example, we have this macro m :

Normally you call it like:

Below call does the same, assuming dynArgs is the hash {'a': 1, 'b': 2, 'c': 3} :

Below call also does the same, but combines dynamic arguments from dynArgsAB , assumed to be {'a': 1, 'b': 2} , and argument c specified directly:

To understand why this works, you need to realize that macros, custom directives, functions, and methods in FreeMarker are just values, just like numbers, strings, etc. <#macro m ... > just creates a value that's a macro (as opposed to a number, or string, etc.), and then assigns it to variable m . Thus, m in itself is a valid expression, which evaluates to the macro (but it doesn't call the macro). <@m ... /> evaluates the expression m (and you can use arbitrarily complex expressions there too, like m?with_args( ... ) ), and then calls the resulting macro. m?with_args( dynArgs ) returns a macro that's very similar to the original macro (that's stored in m ), but its arguments default to the values specified in dynArgs . So the result of m?with_args({'b': 22, 'c': 33}) is similar to a modified macro that was created as <#macro unspefiedName a b=22 c=33> . With an example:

Above we have created a new macro based on the value of m , stored it in variable mWithDefs , and then later we called it with <@myWithDefs ... /> .

with_args can also be applied on functions (crated with <#function ... > ) and Java methods (usually get from the data-model, like myObject.myMethod ). But because functions and methods can only be called with positional arguments (like f(1, 2, 3) , and not as f(a=1, b=2, c=3) ), the argument to with_args must be a sequence instead of a hash. Other than that, the same tricks work as with macros:

Note the double application of ( ... ) above, like in f?with_args( dynArgs )() . That's because f?with_args( dynArgs ) just returns a new function (which is just a value), but doesn't call it. So if you want to call that new function immediately (as opposed to assigning it to a variable for example), you need the second () .

Because macro calls support both named and positional arguments, the with_args argument can be a sequence for macros as well (though using a hash is usually a better practice):

To summarize, depending on the type of the value with_args is applied on, the type of argument to with_args can be:

Function or method: sequence. Note that WRONG f?with_args(1, 2) is WRONG, the correct form is f?with_args([1, 2]) .

Macro: hash or sequence

Directive (user defined): hash

The return type of with_args is the same as the type of value it was applied on, like if it's applied on a method (like myObj.myMethod?with_args(dynArgs) ), then it returns a method.

Note that it's not possible to apply with_args on built-in directives, like <#if ... > , <#list ... > , etc., because they aren't available as values.

This built-in is often used together with the .args special variable . For example:

FreeMarker syntax allows using the name before the ?with_args( ... ) in the end-tag, just as if the ?with_args( ... ) wasn't there:

Note that as far as the order of arguments is concerned, arguments coming from with_args( ... ) are added before the arguments specified in the call to the returned directive/function/method. In some use cases it's more desirable to add them at the end instead, in which case use the with_args_last built-in .

Same as with_args , but if the order of the arguments in resulting final argument list may differs (but not the values in it). This only matters if you pass parameters by position (typically, when calling functions or methods), or when there's catch-all argument.

A typical example with positional arguments is when you want to add the dynamic argument to the end of the parameter list:

In the case of name arguments, while the primary mean of identifying an argument is the its name, catch-all arguments ( others... below) still have an order:

If you specify a named parameter that are not catch-all, so they are declared in the macro tag (as a and b below), then with_args and with_args_last are no different, since the argument order is specified by the macro definition, not the macro call:

If both the macro or directive call, and the with_args_last argument specifies named catch-all argument with the same name (like b below), then the placement of those parameters is decide by the macro/directive call:

  • What is FreeMarker?
  • Version history
  • Privacy policy

Often used / Reference

  • Try template online
  • Expressions cheatsheet
  • .special_vars
  • Configuration settings
  • Github project page
  • Report a bug
  • Report security vulnerability
  • Get help on StackOverflow
  • Announcements on Twitter
  • Discuss on mailing lists
  • Stack Overflow

Last generated: 2024-02-12 20:34:04 GMT , for Freemarker 2.3.32

© 1999 –2024 The Apache Software Foundation . Apache FreeMarker, FreeMarker, Apache Incubator, Apache, the Apache FreeMarker logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.

IMAGES

  1. Using FreeMarker with servlets

    freemarker assign false

  2. OAuth start IdP freemarker template error · Issue #1276 · FusionAuth

    freemarker assign false

  3. Introduction to FreeMarker Templates with Spring Boot

    freemarker assign false

  4. Spring Boot and FreeMarker

    freemarker assign false

  5. [Freemarker] 初识FreeMarker_freemarker w:t 宽度-CSDN博客

    freemarker assign false

  6. [Solved] freemarker templates check if sequence is empty

    freemarker assign false

VIDEO

  1. How to user Liferay Services in free marker template language

  2. Ex 6.2 Q 1

  3. Cách để tạo Project Hibernate với NetBeans bản mới nhất & generate entity từ DB sử dụng SQL Server

  4. Ternary Operator In C

  5. 【 Ktor (FreeMarker) 】 Enabling Auto-Escaping by Setting the 'outputFormat' #ktor #kotlin

  6. Java Ternary Operator (Conditional Operator)

COMMENTS

  1. Built-ins for booleans

    You can use it in two ways: As foo?string ("yes", "no"): Formats the boolean value to the first parameter (here: "yes") if the boolean is true, and to the second parameter (here: "no") if it's false.

  2. assign

    </#assign> Where: name: name of the variable. It is not expression. However, it can be written as a string literal, which is useful if the variable name contains reserved characters, for example <#assign "foo-bar" = 1>.

  3. freemarker

    2 Answers Sorted by: 29 booleanVar?string ("true", "false") Although true/false is default, so booleanVar?string should work fine. Share Improve this answer Follow edited Oct 2, 2009 at 19:37 answered Oct 2, 2009 at 17:59 tsilb 8,017 13 72 99 If I do this I get: "freemarker.core.InvalidReferenceException: Expression booleanVar$string is undefined".

  4. Expressions

    Expressions. When you supply values for interpolations or directive parameters you can use variables or more complex expressions. For example, if x is the number 8 and y is 5, the value of (x + y)/2 resolves to the numerical value 6.5. Before we go into details, let's see some concrete examples:

  5. boolean assignment in freemarker using conditional statements

    1 You haven't included the error message... but I guess your problem is that if the first condition is false, then you never assign to the bool variable, so it won't exist at all, and so you can't use it in the second expression. To fix that, the first #if could to be changed to: [#assign bool = something == value] Share Improve this answer Follow

  6. FreeMarker Manual

    By default, true is rendered as "true" and false is rendered as "false". This is mostly useful if you generate source code with FreeMarker (but use ?c for that starting from 2.3.20) , since the values are not locale (language, country) sensitive. To change these default strings, you can use the boolean_format setting.

  7. FreeMarker Common Operations

    Quick Overview To inject dynamic content in our pages, we need to use a syntax that FreeMarker understands: $ {…} in the template will be replaced in the generated output with the actual value of the expression inside the curly brackets - we call this interpolation - a couple of examples are $ {1 + 2 } and $ {variableName}

  8. Freemarker cheat sheet

    In FreeMarker it is possible to define new variables within the template. This is achieved with the assign directive : Example. Copy <#assign x = 1> ${x} <#assign x = 3*x> ${x} The output will be ... Returns the columns headers if any. (hasHeaders() returns true or false if they exist or not). hasHeaders() : Returns whether the resultSet has ...

  9. FreeMarker Manual

    assign Page Contents Synopsis Description Synopsis <#assign <#assign <#assign ><#assign </#assign><#assign </#assign> Where: name: name of the variable. It is not expression. However, it can be written as a string literal, which is useful if the variable name contains reserved characters, for example <#assign "foo-bar" = 1>.

  10. FreeMarker Manual

    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.

  11. Built-ins for strings

    Apache FreeMarker is a template engine that can process strings and generate dynamic output. This webpage explains the built-in functions that can manipulate strings in FreeMarker, such as upper_case, replace, matches, etc. You can also learn how to use encoding, include, and Jython wrapper features from the related webpages.

  12. FreeMarker: Conditional Statements

    FreeMarker: Conditional Statements A Conditional statement allows you to dynamically determine which content will display in an email for a recipient based on information stored in CRM. For example, you can display specific content in an email template based on the recipient's gender.

  13. Course Module 5. Spring

    You can set the value to true or false depending on your need. Additional form macros make HTML escaping easier to use, and you should use these macros whenever possible. ... <#-- for FreeMarker --> <#assign xhtmlCompliant = true> After processing this directive, all elements created by Spring macros will now be compliant with the XHTML standard.

  14. How to set null to a variable in freemarker

    15 No, there's no "unassign", nor the concept of null exists in FreeMarker (until 2.4.0 at least, but that's far away anyway). It only have missing variables (maybe technically a null, maybe doesn't exist at all) and those that are there. I don't really get why is that needed in your case. Can you show a simplified example of the situation? Share

  15. FAQ

    FreeMarker Pros: 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.

  16. FreeMarker: Boolean Values Test

    A simple test follows:",""," ${message}","","#assign b=true>",""," Now perform scalar boolean tests:",""," #if b>"," b is true.","#else>"," b is false. #if false ...

  17. FreeMarker Manual

    The syntax of this directive is: <#if </#if> . The expression here must evaluate to a boolean value. For example in <#if 2 < 3>2 < 3 (2 is less than 3) is an expression which evaluates to This is a reminder for those of you who already know FreeMarker or are just experienced programmers: "Foo""It's \"quoted\""r"C:\raw\string"

  18. Assigning a variable to an object in Freemarker templates

    1 Answer Sorted by: 6 It is possible, like this: <#assign thisGuy = outter.inner.assignThisGuy> ... ${thisGuy.field1} Share Follow answered Dec 8, 2013 at 10:07 ddekany

  19. Seldom used and expert built-ins

    As you can see, interpret can be applied on a sequence of two items, in which case the first item is the FTL string to interpret, and the second items is the template name used after the "->". The configuration settings that affect the interpreted template are the same as of the surrounding template, except that parser settings specified in the ftl directive or was established via tag syntax ...

  20. Handling null values in Freemarker

    6 Answers Sorted by: 137 Starting from freemarker 2.3.7, you can use this syntax : ${(object.attribute)!} or, if you want display a default text when the attribute is null : ${(object.attribute)!"default text"} Share Follow answered Dec 23, 2014 at 4:46 Arnaud 7,319 10 51 71 2