Thymeleaf:如何在js文件而不是html中获取环境变量
我正在使用 thymleaf 引擎。 我可以在 .html
文件中获取环境变量
。但我无法在 .js
文件中获取环境变量
。如何在 .js
文件而不是 .html
中获取环境变量
?
以下代码显示了我在 .js
和 .html
application.properties
huge=huge
中定义环境变量
时的结果当我定义环境变量
时code> in foo.html
<script type="text/javascript">
hugeOfHtml = "[[${@environment.getProperty('huge')}]]";
</script>
chrome F12 中的结果
<script type="text/javascript">
hugeOfHtml = "huge";
</script>
对比当我在 foo.js
中定义环境变量
时
hugeOfJs = "[[${@environment.getProperty('huge')}]]";
F12 中的结果
hugeOfJs = "[[${@environment.getProperty('huge')}]]";
chrome 获取环境变量
.js
文件不是 .html
?
I am using thymleaf
engine.
I can get environment variable
in .html
file. But I failed to get environment variable
in .js
file. How to get environment variable
in .js
file not .html
?
The following code shows result when I defined environment variable
in .js
and .html
application.properties
huge=huge
When I defined environment variable
in foo.html
<script type="text/javascript">
hugeOfHtml = "[[${@environment.getProperty('huge')}]]";
</script>
The result in chrome F12
<script type="text/javascript">
hugeOfHtml = "huge";
</script>
In contrast to When I defined environment variable
in foo.js
hugeOfJs = "[[${@environment.getProperty('huge')}]]";
The result in chrome F12
hugeOfJs = "[[${@environment.getProperty('huge')}]]";
How to get environment variable
in .js
file not .html
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您使用的是 spring boot 2 和 thymeleaf 3。外部化的 js 文件很可能位于 src/resources/static/ 路径中,如果是这样,那么 thymeleaf 将不会处理它。现在假设您将其移动到另一个目录 src/resources/templates/js/ ,thymeleaf 应该处理外部化的 js 文件并给出您所期望的结果。
但是,鉴于外部化 js 文件不再是静态资源,您必须在控制器中公开 get 方法来加载外部化 js 文件。该方法看起来像这样;
上面的方法将加载外部化的 js 文件,使用 thymeleaf 处理它并相应地返回它。
如果您只使用弹簧;不是 Spring Boot,我相信您还必须创建模板解析器和模板引擎。 这是 Baeldung 的一篇好文章。
I am assuming you are using spring boot 2 and thymeleaf 3. Most probably the externalized js file is located in the
src/resources/static/
path and if so, then thymeleaf will not process it. Now say you move it to another directorysrc/resources/templates/js/
, thymeleaf should process the externalized js file and give the result which you were expecting as you asked.However given the externalized js file is not a static resource anymore, you will have to expose a get method in your controller to load the externalized js file. The method will look like so;
The method above will load the externalized js file, process it using thymeleaf and return it accordingly.
If you are using just spring; not spring boot, I believe you will have to create the template resolver and template engine as well. Here is a good article by Baeldung.