FreeMarker FTL常用指令

本文详细介绍Freemarker模板引擎的使用,包括assign指令用于变量定义,include指令用于模板文件的引入,以及if、list等控制结构的应用。通过实例演示如何在模板中处理数据,实现动态页面生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

freemarker在线手册

assign指令

使用该指令你可以创建一个新的变量, 或者替换一个已经存在的变量。

  • 定义简单类型
<#assign linkman="张小姐">
联系人:${linkman}

在这里插入图片描述

  • 定义对象类型
<#assign info={"mobile":"12345678911","address":"广东深圳"}>
电话:${info.mobile}  地址:${info.address}

在这里插入图片描述

include指令

你可以使用它在你的模板中插入另外一个 FreeMarker 模板文件 (由 path 参数指定)。 被包含模板的输出格式是在 include 标签出现的位置插入的。 被包含的文件和包含它的模板共享变量,就像是被复制粘贴进去的一样。
这个指令不能和JSP(Servlet)的include搞混, 因为它不涉及到Servlet容器中,只是处理应外一个FreeMarker模板, 不能"离开"FreeMarker。

创建模板文件head.ftl

<h1>官方网站</h1>

在模板文件test2.ftl中使用include指令引入模板head.ftl

<body>

<#--include指令-->
<#include "head.ftl">
<#--通常使用 /(斜杠)来分隔路径成分, 而不是 \(反斜杠)。如果你从你本地的文件系统加载模板, 而它使用反斜杠(像Windows操作系统),也要使用 /。-->

<#--我是一个注释,不会输出-->
<!--html注释-->

<#--assign指令:定义对象类型-->
<#assign info={"mobile":"12345678911","address":"广东深圳"}>
电话:${info.mobile}  地址:${info.address}
<br>

</body>

在这里插入图片描述

if, else, elseif 指令

在代码中对变量x赋值

Map map=new HashMap();
map.put("x", 3);

在模板文件上添加

<body>
<#-- if, else, elseif 指令指令 -->
<#--freemarker中“=”与“==”是一个意思-->
<#if x == 1>
  x is 1
<#elseif x == 2>
  x is 2
<#elseif x == 3>
  x is 3
<#elseif x == 4>
  x is 4
<#else>
  x is not 1 nor 2 nor 3 nor 4
</#if>
<br/>

</body>

在这里插入图片描述

list指令

代码中对变量goodsList赋值

		Map map=new HashMap();
		List goodsList=new ArrayList();
		Map goods1=new HashMap();
		goods1.put("name", "苹果");
		goods1.put("price", 5.8);
		Map goods2=new HashMap();
		goods2.put("name", "香蕉");
		goods2.put("price", 2.5);
		Map goods3=new HashMap();
		goods3.put("name", "橘子");
		goods3.put("price", 3.2);
		goodsList.add(goods1);
		goodsList.add(goods2);
		goodsList.add(goods3);
		
		map.put("goodsList", goodsList);

在模板文件上添加

<body>
--------商品价格表--------<br>
<#list goodsList as goods>
<#--如果想在循环中得到索引,使用循环变量+_index就可以得到。-->
  ${goods_index+1} 商品名称: ${goods.name} 价格:${goods.price}<br>
</#list>

</body>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值