我在ftl中有以下代码:
<#macro field label name value="" type="text">
${name}
${name!"print if null"}
<div class="field">
<div class="clearfix" id="${name}_field">
<label for="${name}">${label}</label>
<div class="input">
<input type="${type}" id="${name}" name="${name}" value="${value}">
<span class="help-inline"></span>
<span class="help-block"></span>
</div>
</div>
</div>
</#macro>
<@field label="label" name="test" />
这正在打印:
foo-test
test
<div class="field">
<div class="clearfix" id="foo-test_field">
<label for="foo-test">label</label>
<div class="input">
<input type="text" id="foo-test" name="foo-test" value="">
<span class="help-inline"></span>
<span class="help-block"></span>
</div>
</div>
</div>
foo-test
是我的应用程序的名称,但无法理解为什么它被打印在那里。只需使用 ctrl+f 搜索 foo-test
它不在ftl或 Controller 中......
除此之外,我们假设 name
是一个具有我的应用程序名称的变量。那么为什么第二次打印只打印我传递给宏的正确值?这实在是太奇怪了……
我使用 Maven 和 Spark,所以我有这个依赖项:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-template-freemarker</artifactId>
<version>2.0.0</version>
</dependency>
插件是这样的:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1</version>
<configuration>
<mainClass>com.example.foo.foo-test</mainClass>
</configuration>
</plugin>
</plugins>
</build>
我的 Controller 看起来像这样:
.....
import spark.ModelAndView;
import spark.Spark;
import spark.template.freemarker.FreeMarkerEngine;
......
Spark.get("/foo", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
return new ModelAndView(attributes, "test.ftl");
}, new FreeMarkerEngine());
最佳答案
发生这种情况是因为您已配置 maven 来过滤您的资源,它确实替换了 ${name}
包含您的项目名称的占位符。
删除<resources>
从您的 pom 中或者如果您确实需要资源过滤,您可以排除 ftl-s 文件。
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
顺便说一下maven-resources-plugin
有关 resource filtering 的文档使用 ${name}
准确演示了此行为占位符。 :)
关于java - `name` 作为 freemarker 中断中的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28178768/