2

如果我&在某个字段中有符号(来自 db,无法更改),并且我想通过 freemarker 显示它...但是读取显示(来自 freemarker)&,这样做的方法是什么?

重申一下,我不能事先更改值(或者至少,我不想),我希望 freemarker “取消标记”&。

重复一遍,这是一个与许多其他 xml 一起放置的值。值本身是独立显示的,被标签包围......所以像

<someTag>${wheeeMyValueWithAnAmpersand}<someTag>

结果,我不希望所有的 & 符号都被转义,否则 xml 会看起来很有趣......只是插值中的那个。

4

2 回答 2

2

我的天啊。

我看到了问题:代码是这样写的:

<#escape x as x?xml>
<#import "small.ftl" as my>
<@my.macro1/>
</#escape>

并且我假设 excape 将 excape 中的所有调用 - 这当然是文档所暗示的

http://freemarker.org/docs/ref_directive_escape.html

<#assign x = "<test>"> m1>
  m1: ${x}
</#macro>
<#escape x as x?html>
  <#macro m2>m2: ${x}</#macro>
  ${x}
  <@m1/>
</#escape>
${x}
<@m2/>      

输出将是:

&lt;test&gt;
m1: <test>
<test>
m2: &lt;test&gt;

但是,当您导入文件时,情况似乎并非如此,并且转义...转义!

解决方案: http ://watchitlater.com/blog/2011/10/default-html-escape-using-freemarker/

上面的链接详细说明了如何解决问题。实际上,它归结为加载不同的 FreemakerLoader,它使用转义标记包装所有模板。

class SomeCoolClass implements TemplateLoader {
    //other functions here
    @Override  
    public Reader getReader(Object templateSource, String encoding) throws IOException {  
        Reader reader = delegate.getReader(templateSource, encoding);  
        try {  
            String templateText = IOUtils.toString(reader);  
            return new StringReader(ESCAPE_PREFIX + templateText + ESCAPE_SUFFIX);  
        } finally {  
            IOUtils.closeQuietly(reader);  
        }  
    }  

这是上面链接的一个片段。您使用现有的 templateLoader 创建类,并将所有必需的方法推迟到该类中。

于 2012-12-06T23:04:15.773 回答
2

从 FreeMarker 2.3.24 开始,TemplateLoader不再需要“hack”。有一个名为 的设置output_format,它指定是否需要转义以及需要转义的内容。这可以在全局和/或使用该template_configurations设置的每个模板名称模式下进行配置。这样做的推荐方法更简单(来自手册):

[...] 如果 recognize_standard_file_extensions设置为true(默认incompatible_improvements设置为 2.3.24 或更高版本),源名称以“.ftlh”结尾的模板将获得“HTML”输出格式,而那些以“.ftlx”结尾的模板获取“XML”输出格式

于 2016-07-23T17:48:51.933 回答