【模板】模板变量`${xxx}`与JS的模板语法冲突

  • 把js代码放到独立的js文件中,通过<script src="xxx.js" />引用到模板中

  • 使用模板标签

<script>
    <#escape x as x?html>
    // 这里面的 ${} 会被JavaScript解释
    var template = `User: ${userName}, Time: ${new Date()}`;
    </#escape>
</script>
  • 修改FreeMarker的插值语法配置

修改FreeMarkerConfig.java中的freemarker配置

freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_34);
// 添加插值语法配置
cfg.setInterpolationSyntax(Configuration.SQUARE_BRACKET_INTERPOLATION_SYNTAX);

模板中是使用[=xxx]来获取插值

<!-- 修改前 -->
${Content.title}
<!-- 修改后 -->
[=Content.title]

内容导航