2017-06-21 23 views
0

我想在我的Thymeleaf模板中使用自動完成jQuery組件。 Materializecss前端framwork的自動完成功能如下:如何使用Thymeleaf將JSON對象內嵌到JavaScript中

$('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 documentation

<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 1.5.4引導,Thymeleaf 3.0.2

+0

當你說Thymeleaf沒有在這種情況下內聯任何東西時,你是什麼意思? js代碼將在哪裏? 靜態模板中? – inoabrian

+0

@inoabrian我的javascript文件是HTML的外部。 – Roland

回答

1

th:inline="javascript"只能如果您的腳本是內聯,這是<script></script>之間的HTML模板。

如果你有一個單獨的JavaScript文件和Thymeleaf表達式,你需要通過Thymeleaf分別使用JAVASCRIPT模板模式來處理這個js文件。

+0

這聽起來很合理。你能告訴我我該怎麼做?我使用Spring Boot,它是自動配置。默認的模板模式是HTML。我怎樣才能爲.js文件指定不同的模板模式?數據:[($ {companies})],/ * unescape * /, 數據:[[$ {companies}]],/ *轉義我也不明白爲什麼javascript模板模式不是js文件的默認值 – Roland

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

嘗試上面的代碼。我也經歷過。

+0

*/ ,Unescape和Escape Expression互不相同 –

+0

參考:https://github.com/thymeleaf/thymeleaf/issues/395 –

相關問題