`
tianhandigeng
  • 浏览: 374513 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

freemarker的空值和默认值

 
阅读更多

Welcome ${user!}!
Welcome ${user!'your name'}!

如果user找不到值,会输出
Welcome !
Welcome your name!



官方说法:

3.  Why is FreeMarker so picky about null -s and missing variables, and what to do with it?
 

To recapitulate what's this entry is about: FreeMarker by default treats an attempt to access a non-existent variable or a null value (this two is the same for FreeMarker ) as error, which aborts the template execution.

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 null -s), and they usually treat them as empty string and/or 0 and/or logical false. This behavior has several problems:

  • 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 <#if hasDetp>print dept here... </#if> , which would then silently never print the dept of the visitor, since you have mistyped the variable name (it should be hasDept ). Also think about maintenance, when you later modify your application... most probably you will not re-check templates that carefully each time.

  • 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 Balance: ${balanace} )? 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 <#if hasPenicilinAllergy>Warning... <#else>Allow... </#if> ; 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.

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.

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:

  • It's often normal that your data model contains null -s or have optional variables. In such cases use these operators . 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).

  • On a production server you may rather want to show an incomplete/damaged page than an error page. In this case you can use other error handler 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: the attempt /recover directives )

15.  What about null and the FreeMarker template language?
 

The FreeMarker template language doesn't know the Java language null at all. It doesn't have null keyword, and it can't test if something is null or not. When it technically faces with a null , it treats it exactly as a missing variable. For example, both if x is null in the data model and if it's not present at all, ${x!'missing'} will print ``missing'', you can't tell the difference. Also, if for example you want to test if a Java method has returned null , just write something like <#if foo.bar()??> .

You may interested in the rationale behind this. From the viewpoint of the presentation layer a null 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 null (unlike in Java); it doesn't make sense to compare something with null in a template, since the template language doesn't do identity comparison (like the Java == operator when you compare two objects) but the more common sense value comparison (like Java's Object.equals(Object) ; that doesn't work with null 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.

There is at least one problem with this null -unaware approach. When you call a Java method from a template, you may want to pass a null value as argument (since the method was designed to be used in Java language, where the concept of null 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 null values to a method): if you specify a missing variable as the argument, then it will not cause an error, but a null will be passed to the method instead. Like foo.bar(nullArg) will call the bar method with null as argument, assuming that there is no varaible exists with ``nullArg'' name.

0
3
分享到:
评论

相关推荐

    freemarker中文手册

    根据提供的文档片段,本文将详细介绍FreeMarker模板语言中的关键概念与用法,尤其是关于处理空值、默认值以及列表遍历的部分。 #### 一、处理空值和默认值 FreeMarker提供了一种简便的方式来处理空值与默认值的...

    freemarker资料集

    FreeMarker支持条件语句(`&lt;#if&gt;`, `&lt;#else&gt;`, `&lt;#elseif&gt;`)和循环(`&lt;#list&gt;`)等控制流,允许在模板中进行条件判断和迭代。 7. **指令(Directives)**: 指令用于控制模板的结构和行为,如`include`用于包含...

    freemarker判断对象是否为空的方法

    FreeMarker是一个强大的模板引擎,它使用...这些工具使得我们能够在模板中安全地处理可能为空的对象和属性,避免了因引用空值而引发的错误。在实际开发中,根据具体情况选择合适的方法,可以使代码更加健壮和易于维护。

    freemarker04

    Freemarker是一个强大的Java模板引擎,常用于动态...通过以上这些方法,你可以有效地在Freemarker模板中处理空值,保证程序的稳定性和用户体验。理解并熟练运用这些技巧,将使你的Freemarker模板代码更加健壮和易维护。

    freemarker(FTL)常见语法大全

    Freemarker使用简单直观的语法,使得开发者能够轻松地将数据模型与表现层分离,从而提高代码的可维护性和复用性。 #### 插值表达式 Freemarker支持两种类型的插值表达式: 1. **通用插值**:`"${expr}"`,用于...

    freemarker总结

    这里所说的空值,实际上也包括那些并不存在的变量,对于一个Java的 null值而言,我们认为这个变量是存在的,只是它的值为null,但对于FreeMarker模板而言,它无法理解null值,null值和不存在的变 量完全相同. 为了处理缺失...

    FreeMarker开发指南

    - **默认值**:可以给变量设定默认值,避免空值异常。 - **null检查**:判断对象是否为null。 - **日期格式化**:对日期进行格式化处理。 - **全局共享变量**:在模板间共享数据。 - **调用Java对象方法**:...

    freemarker教程

    ### Freemarker教程详解 #### 一、Freemarker简介 Freemarker是一个用Java语言编写的模板引擎,...Freemarker的强大之处在于其灵活性和可扩展性,使得开发者可以根据自己的需求定制模板,从而提高开发效率和代码质量。

    java Freemarker页面静态化实例详解

    API是Java代码,用于与Freemarker引擎交互,数据是传递给模板以生成输出的信息,而FTL文件则是包含Freemarker语法的文本文件,用于定义页面布局和动态内容。 以下是一个简单的Freemarker入门实例,展示了如何使用...

    freemark开发指南

    - **默认值**:为变量设置默认值,避免空值时出错。 - **null判断**:检查对象是否为null,避免空指针异常。 - **日期格式化**:使用内置的日期时间函数进行日期格式化。 - **全局共享变量**:在Freemarker配置...

    freemark开发指南(入门)

    本篇将深入介绍Freemarker的基础知识和高级特性。 1. **基础概念** - **Sequence**:在Freemarker中,Sequence代表有序的数据集合,类似于Java中的List或数组。它可以包含任意类型的元素,如数字、字符串或自定义...

    4ftl数值计算和默认value以及value转换1

    `request`, `session` 通常指的是 HTTP 请求对象和会话对象,在 FreeMarker 中可以用来访问请求参数、会话数据等。 以上是 FreeMarker 中的一些基础操作,实际上,它还支持更复杂的逻辑控制、迭代、条件判断等功能...

    资源前后端分离式分布式微服务架构项目CMS页面静态化讲义+源码+视频

    - **空值处理**:通过设置默认值(如`!`操作符)来处理可能出现的空值。 - **示例代码**:通过编写简单的FreeMarker程序来演示如何使用这些指令。 #### 二、页面静态化核心实现 ##### 2.1 轮播图DataUrl接口开发 ...

Global site tag (gtag.js) - Google Analytics