`name` 作为 freemarker 中断中的变量名

`name` as a variable name in freemarker breaks

我在 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 或控制器...

除此之外,我们假设 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>

我的控制器看起来像这样:

    .....

    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());

很奇怪...它应该有用,而且对我有用。我怀疑在 FreeMarker 解析之前在该模板中搜索并替换了 ${name}(例如自定义 TemplateLoader-s 可以做到这一点)。比如,如果你写 ${name<#-- just a comment -->} 而不是 ${name} 会发生什么?

发生这种情况是因为您配置了 Maven 来过滤您的资源,它将 ${name} 占位符替换为您的项目名称。

从您的 pom 中删除 <resources>,或者如果您确实需要资源过滤,您可以排除 ftl-s 文件。

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
    </resource>
</resources>

顺便说一句,关于 resource filteringmaven-resources-plugin 文档用 ${name} 占位符演示了这种行为。 :)