为什么“_csrf”属性在 spring-boot velocity view <head> 标签内没有解析?

Why is "_csrf" attribute not resolved inside spring-boot velocity view <head> tags?

我有一个 Spring-Boot 项目,其中 Velocity 模板化了所有配置并且工作正常...

在我的速度视图中,我有以下内容;

<head>
    <!-- some other meta tags here -->

    <meta name="csrf-token" content="$!_csrf.token">
</head>

这是我在 chrome 中检查时的输出结果;

<meta name="csrf-token" content="$!_csrf.token">


但是在同一页面上,我有一个看起来像这样的表单;

<form method="post" action="/post/to/wherever">
    <input type="hidden" id="csrf" name="$!_csrf.parameterName" value="$!_csrf.token" data-header="$!_csrf.headerName"/>

    <!-- other fields here -->

</form>

浏览器检查显示如下;

<input type="hidden" name="_csrf" value="69799b81-7c45-4042-9269-3a83769df682" data-header="X-CSRF-TOKEN">

很明显,_csrf 属性在 form 主体内被注入和解析,但不在 head 元标签。

问题:什么会导致这样的事情?

好吧,我最终发现这里发生的事情是由于一个非常简单的疏忽。

我在一个单独的模板中有 <head>...</head> 部分,并将其包含到其他模板中,如下所示;

#include("/pages/common/header.vm")

好吧,对于 velocity 的用户来说,很明显上面只包含模板原样(即所有内容都翻译为文本)并且不会解析其中声明的任何 velocity 上下文属性。所以我只需要将其更改为以下内容

#parse("/pages/common/header.vm")

这确保在 header.vm 模板中声明的任何速度属性都得到适当的解析,并相应地读取值。

我最初打算删除这个问题,认为它一开始就不应该被问到,但我意识到,这就是 Whosebug, 最好只是指出错误并为其他人节省一些时间。从本质上讲,让世界对每个人来说都变得更美好……干杯!