LoginSignup
9
5

More than 3 years have passed since last update.

freemakerのメモ

Last updated at Posted at 2019-06-01

JAVA系はfreemarkerはよく使うテンプレートエンジンです。

freemarkerとは

Apache FreeMarker™ is a template engine: a Java library to generate text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data.

freemarker変数定義、存在チェック

変数定義例

freemarkerではnull付与するとエラーになります。
変数定義にエラーが回避するために、初期値を設定したほうがよいです。

error.ftl
<#-- 新変数名 = "固定時文字" の形で初期値設定できます。-->
<#assign userName = "山田">

<#-- 新変数名 = 変数名!初期値 の形で初期値設定できます。-->
<#assign userName = loginUserName!"(記入していない)">

<#-- 新変数名 =  変数名! の形で初期値設定しないが、エラー回避-->
<#assign userName = loginUserName!>

<#-- 新変数名 =  変数名 初期値がないとエラー-->
<#assign userName = loginUserName">

存在チェック例

sample.ftl


<#--変数定義あり、データは空白でない-->
<#assign content = "123" />
<#if content?has_content>
   サンプルデータ(content):${content}
<#else>
   サンプルデータ(content):(空白)
</#if>

<#--変数定義あり、データは空白-->
<#assign emptyContent = "" />
<#if emptyContent?has_content>
   サンプルデータ(emptyContent ):${emptyContent }
<#else>
   サンプルデータ(emptyContent ):(空白)
</#if>


<#--変数定義なし、「?has_content」で存在判断-->
<#if notExistData?has_content>
   サンプルデータ(notExistData):${notExistData}
<#else>
   サンプルデータ(notExistData):(定義していない)
</#if>

<#--変数定義なし、「??」で存在判断-->
<#if notExistData?has_content>
   サンプルデータ(notExistData):${notExistData}
<#else>
   サンプルデータ(notExistData):(定義していない)
</#if>

結果:

サンプルデータ(content):123
サンプルデータ(emptyContent ):(空白)
サンプルデータ(notExistData):(定義していない)
サンプルデータ(notExistData):(定義していない)

異常処理(recover)

<#attempt>
普通処理
<#recover>
普通処理にエラーがある場合、ここのコードを実行
</#attempt>

例:

recover.ftl
<#-- 異常なしの場合 -->
<#attempt>
  正常処理: ${1+1}
<#recover>
  異常処理:異常ありました。
</#attempt>

<#-- 異常ありの場合 -->
<#attempt>
  正常処理: ${nodata}
<#recover>
  異常処理:異常ありました。
</#attempt>

出力:

正常処理: 2
異常処理:異常ありました。

オンラインデモサイト

以上

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5