`

Freemarker

    博客分类:
  • J2EE
阅读更多

Dealing with missing variables

In practice the data-model often has variables that are optional (i.e., sometimes missing). To spot some typical human mistakes, FreeMarker doesn't tolerate the referring to missing variables unless you tell them explicitly what to do if the variable is missing. Here we will show the two most typical ways of doing that.

Note for programmers: A non-existent variable and a variable with null value is the same for FreeMarker, so the "missing" term used here covers both cases.

Wherever you refer to a variable, you can specify a default value for the case the variable is missing, by followin the variable name with a ! and the default value. Like in the following example, when user is missing from data model, the template will behave like if user 's value were the string "Anonymous" . (When user isn't missing, this template behaves exactly like if !"Anonymous" were not there):

<h1>Welcome ${user!"Anonymous"


}!</h1>  


You can ask whether a variable isn't missing by putting ?? after its name. Combining this with the already introduced if directive you can skip the whole greeting if the user variable is missing:

<#if user??


><h1>Welcome ${user}!</h1></#if>  


Regarding variable accessing with multiple steps, like animals.python.price , writing animals.python.price!0 is correct only if animals.python is never missing and only the last subvariable, price , is possibly missing (in which case here we assume it's 0 ). If animals or python is missing, the template processing will stop with an "undefined variable" error. To prevent that, you have to write (animals.python.price)!0 . In that case the expression will be 0 even if animals or python is missing. Same logic goes for ?? ; animals.python.price?? versus (animals.python.price)?? .

 

-----------------------------------------------------------------------------------------------------------------------

 

Function/method versus user-defined directive

This is for advanced users again (so ignore it if you don't understand). It's a frequent dilemma if you should use a function/method or an user-defined directive to implement something. The rule of thumb is: Implement the facility as user-defined directive instead of as function/method if:

  • ... the output (the return value) is markup (HTML, XML, etc.). The main reason is that the result of functions are subject to automatic XML-escaping (due to the nature of ${... } ), while the output of user-defined directives are not (due to the nature of <@... > ; its output is assumed to be markup, and hence already escaped).

  • ... it's the side-effect that is important and not the return value. For example, a directive whose purpose is to add an entry to the server log is like that. (In fact you can't have a return value for a user-defined directive, but some kind of feedback is still possible by setting non-local variables.)

  • ... it will do flow control (like for example list or if directives do). You just can't do that with a function/method anyway.

The Java methods of FreeMarker-unaware Java objects are normally visible as methods in templates, regardless of the nature of the Java method. That said, you have no choice there.

----------------------------------------------------------------------------------------------------------------------------------

An FTL tag can't be inside another FTL tag nor inside an interpolation . For example this is WRONG : <#if <#include 'foo'>='bar'>...</#if>

----------------------------------------------------------------

Warning!

A frequent mistake of users is the usage of interpolations in places where it shouldn't/can't be used. Interpolations work only in text sections (e.g. <h1>Hello ${name}!</h1> ) and in string literals (e.g. <#include "/footer/${company}.html"> ). A typical bad usage is <#if ${isBig}>Wow!</#if> , which is syntactically WRONG . You should simply write <#if isBig>Wow!</#if> . Also, <#if "${isBig}">Wow!</#if> is WRONG too, since the parameter value will be a string, and the if directive wants a boolean value, so it will cause a runtime error.

-----------------------------------------------------------------

You can concatenate hashes in the same way as strings, with + . If both hashes contain the same key, the hash on the right-hand side of the + takes precedence.

-----------------------------------------------------------------------------------

Generally, FreeMarker never converts a string to a number automatically, but it may convert a number to a string automatically.

---------------------------------------------------------------------------------

${(x/2)?int}
${1.1?int}
${1.999?int}
${-1.1?int}
${-1.999?int}  


Assuming that x is 5, it will print:

2
1
1
-1
-1  


--------------------------------------------------------------------------

User-defined directives can have multiple parameters. For example, add a new parameter color :

<#macro greet person color

>
  <font size="+2" color="${color}">Hello ${person}!</font>
</#macro>  

and then you can use this macro like:

<@greet person="Fred" color="black"/>  

---------------------------------------------------------------------------------------

<#macro border>
  <table border=4 cellspacing=0 cellpadding=4><tr><td>
    <#nested>


  </tr></td></table>
</#macro>  

The <#nested> directive executes the template fragment between the start-tag and end-tags of the directive. So if you do this:

<@border>The bordered text</@border>  

the output will be:

  <table border=4 cellspacing=0 cellpadding=4><tr><td>
    The bordered text
  </td></tr></table>
  

---------------------------------------------------------------------------------------------

The expressions on both sides of the = or != must evaluate to a scalar. Furthermore, the two scalars must have the same type (i.e. strings can only be compared to strings and numbers can only be compared to numbers, etc.)

--------------------------------------------------------------------------------

There is a little problem with >= and > . FreeMarker interprets the > as the closing character of the FTL tag. To prevent this, you have to put the expression into parenthesis : <#if (x > y)> . Or, you can use &gt; and &lt; on the place of the problematic relation marks: <#if x &gt; y> .

------------------------------------------------------------------------------------------------------

  • Built-ins to use with strings:

    • html : The string with all special HTML characters replaced with entity references (E.g. < with &lt; )

    • cap_first : The string with the first letter converted to upper case

    • lower_case : The lowercase version of the string

    • upper_case : The uppercase version of the string

    • trim : The string without leading and trailing white-spaces

  • Built-ins to use with sequences:

    • size : The number of elements in the sequence

  • Built-ins to use with numbers:

    • int : The integer part of a number (e.g. -1.9?int is -1 )

    ${test?html}
    ${test?upper_case?html}  
    
    
    

    Assuming that test stores the string ``Tom & Jerry'', the output will be:

    Tom &amp; Jerry
    TOM &amp; JERRY  
    
    
    
    ----------------------------------------------------------------------------------------
  • Synopsis: unsafe_expr !default_expr or unsafe_expr ! or (unsafe_expr )!default_expr or (unsafe_expr )!

    This operator allows you to specify a default value for the case when the value is missing.

----------------------------------------------------------------------------------------------------------------
However, you can convert booleans to strings with the ?string built-in . For example, to print the value of the "married" variable (assuming it's a boolean), you could write ${married?string("yes", "no")} .
----------------------------------------------------------------------------------------------------------------

 

A special kind of string literals is the raw string literals. In raw string literals, backslash and ${ have no special meaning, they are considered as plain characters. To indicate that a string literal is a raw string literal, you have to put an r directly before the opening quotation mark or apostrophe-quote. Example:

${r"${foo}"}
${r"C:\foo\bar"}  


will print:

 

 

 

 

 

${foo}
C:\foo\bar  



分享到:
评论

相关推荐

    freemarker 自定义freeMarker标签

    本篇将深入探讨如何自定义FreeMarker标签,以扩展其功能并适应特定项目需求。 首先,理解FreeMarker的默认标签语法至关重要。FreeMarker使用${...}表达式来插入变量,#{...}用于输出注释,以及、等控制结构进行条件...

    eclipse的freemarker插件

    而Freemarker则是一种轻量级的、基于模板的Java模板引擎,常用于Web应用中的动态内容生成,比如JSP替代技术。它允许开发者将业务逻辑与页面展示分离,提高代码的可维护性和可读性。 "eclipse的freemarker插件"是指...

    FreeMarker

    FreeMarker的设计理念是将表现层(视图)和业务逻辑层(控制器)分离,从而实现MVC(Model-View-Controller)架构中的“View”部分。 FreeMarker的核心概念是模板文件,这是一种特殊的文本文件,其中包含可替换的...

    freemarker-2.3.23jar

    `freemarker-2.3.23.jar`是Freemarker库的一个版本,发布于2.3.23,这个版本可能包含了对早期版本的一些改进、新功能或bug修复。 Freemarker的核心概念是模板语言,它是一种声明式的编程方式,允许开发者编写不包含...

    freemarker解析成pdf

    1. **创建模板**:在Freemarker中,我们需要创建一个`.ftl`(Freemarker Template Language)文件,其中包含静态文本和动态占位符。动态占位符由${}或#{}包裹,用于插入数据模型中的值。例如,`${title}&lt;/h1&gt;`会将...

    freemarker-2.3.28.jar

    这个"freemarker-2.3.28.jar"是Freemarker库的一个具体版本,版本号为2.3.28,它是Java的一个可执行的JAR(Java Archive)文件,用于在Eclipse集成开发环境中作为插件使用。 在Freemarker的2.3.28版本中,我们可以...

    freemarker-ide插件

    Freemarker-IDE是一款专为开发人员设计的Eclipse插件,它主要针对Freemarker模板语言提供了强大的支持。在Eclipse这样的集成开发环境中,这款插件能够显著提升开发人员编写和调试`.ftl`(FreeMarker Template ...

    freemarker-2.3.31-API文档-中文版.zip

    赠送jar包:freemarker-2.3.31.jar; 赠送原API文档:freemarker-2.3.31-javadoc.jar; 赠送源代码:freemarker-2.3.31-sources.jar; 赠送Maven依赖信息文件:freemarker-2.3.31.pom; 包含翻译后的API文档:...

    FreeMarker2.3.23官方中文文档

    2.3.23是FreeMarker的一个稳定版本,这个版本的官方中文文档提供了全面的指导和说明,帮助开发者更好地理解和使用这个模板语言。 在FreeMarker的核心概念中,它是一个基于数据驱动的模板语言。这意味着,开发者不...

    freemarker-2.3.30-API文档-中文版.zip

    赠送jar包:freemarker-2.3.30.jar; 赠送原API文档:freemarker-2.3.30-javadoc.jar; 赠送源代码:freemarker-2.3.30-sources.jar; 赠送Maven依赖信息文件:freemarker-2.3.30.pom; 包含翻译后的API文档:...

    Velocity 和 FreeMarker区别

    ### Velocity与FreeMarker的区别 在IT领域特别是Java开发中,模板引擎是不可或缺的一部分,它们用于将数据模型转换为HTML、PDF、Word文档等格式。在众多模板引擎中,Velocity和FreeMarker是两种非常受欢迎的选择。...

    模板:velocity和freemarker的比较

    Velocity和Freemarker模板技术比较 模板技术在现代软件开发中扮演着重要角色,而在目前最流行的两种模板技术中, Velocity 和 Freemarker 独占鳌头。在 WebWork2 中,我们可以随意选择使用 Freemarker 或 Velocity ...

    Freemarker简介及标签详解大全

    Freemarker 简介及标签详解大全 FreeMarker 是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯 Java 编写。FreeMarker 被设计用来生成 HTML Web 页面,特别是基于 MVC 模式的应用程序。虽然 FreeMarker ...

    freemarker

    标题:Freemarker 描述:孔浩的Freemarker视频笔记,值得一看! 根据给定的文件信息,我们可以深入探讨Freemarker的相关知识点,包括其基本概念、工作流程以及具体的代码实现。 ### Freemarker基本概念 ...

    freemarker生成xml示例

    这个示例是关于如何使用Freemarker来生成XML文件,对于初学者来说,理解这个过程有助于掌握Freemarker的基本用法和XML的生成技巧。 在Java中,Freemarker与数据模型结合,通过模板文件生成输出。对于XML生成,首先...

    可视化div布局 生成freemarker模板

    本话题主要探讨的是如何利用可视化div布局来生成FreeMarker模板,并结合Spring MVC 3框架进行应用。下面将详细阐述这些概念及其相关知识点。 1. **FreeMarker模板引擎**:FreeMarker是一个开源的Java模板引擎,它...

    通过freemarker模板 生成PDF

    本主题将深入探讨如何利用Freemarker模板和wkhtmltox工具来实现这一功能。 **Freemarker模板** 是一个强大的Java模板引擎,用于动态生成文本输出,如HTML、XML或PDF。它支持变量替换、控制结构(如if/else)和复杂...

    FreeMarker通用的分页

    FreeMarker提供了一种灵活且强大的方式来处理动态内容,尤其适用于Web开发中的视图层。在FreeMarker中实现通用的分页功能是提高Web应用程序性能和用户体验的重要一环。 ### FreeMarker通用分页知识点解析 #### 1. ...

    freemarker Demo 适用于freemarker初学

    Freemarker是一个强大的模板引擎,常用于JavaEE应用中的视图层处理,尤其与Struts2等MVC框架配合使用,能实现灵活的动态页面渲染。这个"freemarker Demo"是一个适合初学者的示例项目,旨在帮助新接触Freemarker的...

    FreeMarker中文文档.pdf下载

    根据提供的文件信息,我们可以深入探讨FreeMarker的相关知识点及其在网页模板设计中的应用。FreeMarker是一种用Java编写的模板引擎,其主要用途在于帮助开发者高效地生成动态内容,尤其是在Web开发领域有着广泛的...

Global site tag (gtag.js) - Google Analytics