提问者:小点点

如何内联JSON对象到JavaScript与Thymeleaf


我想在我的Thymeleaf模板中使用自动完成jquery组件。Materializecss前端框架的自动完成功能如下所示:

$('input.autocomplete').autocomplete({
    data: {
      "Apple": null,
      "Microsoft": null,
      "Google": 'http://placehold.it/250x250'
    },
    limit: 20, // The max amount of results that can be shown at once. Default: Infinity.
    onAutocomplete: function(val) {
      // Callback function when value is autcompleted.
    },
    minLength: 1, // The minimum length of the input for the autocomplete to start. Default: 1.
  });

如您所见,我需要一个包含元素列表的数据对象。我想从服务器端嵌入这个变量,因为这个列表是动态的。正如Thymeleaf留档所说

<script type="text/javascript" th:inline="javascript" th:src="@{/js/example.js}"></script>

基于留档,以下示例应该可以工作:

$('input.autocomplete').autocomplete({
        data: [[${companies}]],
        limit: 20, // The max amount of results that can be shown at once. Default: Infinity.
        onAutocomplete: function(val) {
          // Callback function when value is autcompleted.
        },
        minLength: 1, // The minimum length of the input for the autocomplete to start. Default: 1.
      });

问题是在这种情况下,Thymeleaf没有内联任何东西。嵌入服务器端变量或命令对象可以在Thymeleaf中正常工作,但我无法使其适用于javascript。我使用Spring Boot 1.5.4,Thymeleaf 3.0.2


共2个答案

匿名用户

th: inline="javascript"仅在您的脚本是内联的情况下有效,即在之间的超文本标记语言模板中

如果您有一个单独的javascript文件和要在其中评估的Thymeleaf表达式,则需要使用JAVASCRIPT模板模式通过Thymeleaf单独处理该js文件。

匿名用户

$('input.autocomplete').autocomplete({
    data: [($ {
        companies
    })], // use  '(', ')'
    limit: 20,
    onAutocomplete: function(val) {},
    minLength: 1
});

试试上面的代码。我也经历过。