Thymeleaf 如何在 javascript 中添加条件块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31771821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:21:04  来源:igfitidea点击:

Thymeleaf How to add conditional block in javascript

javascriptthymeleaf

提问by Youssef Al Muhaidib

I have a web application and using Thymeleaf with spring boot, I need to include an option in my javascript in-case the user locale was Arabic, so how add a conditional block and should be processed at server side?

我有一个 Web 应用程序并使用 Thymeleaf 和 spring boot,我需要在我的 javascript 中包含一个选项,以防用户语言环境是阿拉伯语,那么如何添加条件块并应在服务器端处理?

<script th:inline="javascript">
        var customerNameTitle = /*[[#{pendingPayments.customerName}]]*/ 'customer Name';
        var amountTitle = /*[[#{pendingPayments.amount}]]*/ 'Amount';
        var paymentDateTitle = /*[[#{pendingPayments.paymentDate}]]*/ 'payment Date';
        var submissionDateTitle = /*[[#{pendingPayments.submissionDate}]]*/ 'submission Date';

        $("document").ready(function(e) {
            /*<![CDATA[*/
               var table = $("#example").DataTable( {
                    "ajax": {
                                "url": /*[[@{/payments/getPendingPayments}]]*/ "",
                                "type": "GET",
                                "dataSrc": ""
                            },
                    "columns": [
                                { "data": "customerFullName", "title": customerNameTitle },
                                { "data": "amount", "title": amountTitle },
                                { "data": "paymentDate", "title": paymentDateTitle },
                                { "data": "submissionDate", "title": submissionDateTitle },
                            ],
                    "language": {
                                "emptyTable": /*[[#{pendingPayments.emptyTable}]]*/ "",
                                "url":/*[[@{'/json/dataTables-ar.json'}]]*/ ""
                              }
                });
            /*]]>*/
           });
    </script>

the "url":/*[[@{'/json/dataTables-ar.json'}]]*/should only be loaded if the locale is Arabic, otherwise the the whole line shouldn't be printed in HTML page..

"url":/*[[@{'/json/dataTables-ar.json'}]]*/如果语言环境是阿拉伯语,否则整条生产线不应该在HTML页面打印只应加载..

in JSTL I can do that using <c:if>

在 JSTL 中,我可以使用 <c:if>

<c:if test="${LOCALE.language eq 'ar' }">
    ....
</c:if>

is there an equivalent in Thymeleaf?

Thymeleaf 中是否有等价物?

回答by bernie

The closest I found in Thymeleaf 2 is to add a th:ifcondition to the whole <script>tag. You can then have multiple <script>tags but of course there will be come copy-pasting involved.

我在 Thymeleaf 2 中发现的最接近的是向th:if整个<script>标签添加一个条件。然后您可以拥有多个<script>标签,但当然会涉及复制粘贴。

This feature is available in Thymeleaf 3

此功能在 Thymeleaf 3 中可用

<script th:inline="javascript">
    var customerNameTitle = /*[[#{pendingPayments.customerName}]]*/ 'customer Name';
    var amountTitle = /*[[#{pendingPayments.amount}]]*/ 'Amount';
    var paymentDateTitle = /*[[#{pendingPayments.paymentDate}]]*/ 'payment Date';
    var submissionDateTitle = /*[[#{pendingPayments.submissionDate}]]*/ 'submission Date';

    $("document").ready(function(e) {
        /*<![CDATA[*/
           var table = $("#example").DataTable( {
                "ajax": {
                            // Using textual syntax from Thymeleaf 3
                            // (not sure about the exact condition for your case
                            // but this is the syntax to use)
                            [# th:if="${LOCALE.language.equals('ar') }"]
                            "url": /*[[@{/payments/getPendingPayments}]]*/ "",
                            [/]
                            "type": "GET",
                            "dataSrc": ""
                        },
                "columns": [
                            { "data": "customerFullName", "title": customerNameTitle },
                            { "data": "amount", "title": amountTitle },
                            { "data": "paymentDate", "title": paymentDateTitle },
                            { "data": "submissionDate", "title": submissionDateTitle },
                        ],
                "language": {
                            "emptyTable": /*[[#{pendingPayments.emptyTable}]]*/ "",
                            "url":/*[[@{'/json/dataTables-ar.json'}]]*/ ""
                          }
            });
        /*]]>*/
       });
</script>

See the Thymeleaf textual syntaxin https://github.com/thymeleaf/thymeleaf/issues/395

Thymeleaf文本语法https://github.com/thymeleaf/thymeleaf/issues/395

回答by amdg

Although, a old question, the following worked for us.

虽然是一个老问题,但以下内容对我们有用。

    <script th:inline="javascript">
    /*<![CDATA[*/
      var isInlineEdit = [[${param.isInlineEdit} != null ? true:false]];

      if(isInlineEdit){
        //in line edit code
      }else{
        //no in line edit
      }
    /*]]>*/
    </script>

回答by nmy

I couldn't find a way to do this, but alternatively you can do something like this.

我找不到办法做到这一点,但你也可以做这样的事情。

Define a js variable with the expression you want & use it.

使用您想要的表达式定义一个 js 变量并使用它。

var condition = /*[[${LOCALE.language eq 'ar' }]]*/ 'true';

$("document").ready(function(e) {
        /*<![CDATA[*/
        if( condition) {
           var table = $("#example").DataTable( {
                "ajax": {
                            "url": /*[[@{/payments/getPendingPayments}]]*/ "",
                            "type": "GET",
                            "dataSrc": ""
                        },
                "columns": [
                            { "data": "customerFullName", "title": customerNameTitle },
                            { "data": "amount", "title": amountTitle },
                            { "data": "paymentDate", "title": paymentDateTitle },
                            { "data": "submissionDate", "title": submissionDateTitle },
                        ],
                "language": {
                            "emptyTable": /*[[#{pendingPayments.emptyTable}]]*/ "",
                            "url":/*[[@{'/json/dataTables-ar.json'}]]*/ ""
                          }
            });
        }
        else {
          var table = $("#example").DataTable( {
                "ajax": {
                            "url": /*[[@{/payments/getPendingPayments}]]*/ "",
                            "type": "GET",
                            "dataSrc": ""
                        },
                "columns": [
                            { "data": "customerFullName", "title": customerNameTitle },
                            { "data": "amount", "title": amountTitle },
                            { "data": "paymentDate", "title": paymentDateTitle },
                            { "data": "submissionDate", "title": submissionDateTitle },
                        ],
                "language": {
                            "emptyTable": /*[[#{pendingPayments.emptyTable}]]*/ ""
                          }
            });
        }
        /*]]>*/
       });

回答by Blejzer

Taken from Thymeleaf tutorial:

取自 Thymeleaf 教程:

Expression Basic Objects

When evaluating OGNL expressions on the context variables, some objects are made available to expressions for higher flexibility. These objects will be referenced (per OGNL standard) starting with the # symbol:...#locale: the context locale...

表达式基本对象

在上下文变量上评估 OGNL 表达式时,某些对象可用于表达式以获得更高的灵活性。这些对象将被引用(根据 OGNL 标准)从 # symbol:...#locale: the context locale...

OGNL stands for Object-Graph Navigation Language. So actual usage would look like this:

OGNL 代表对象图导航语言。所以实际使用应该是这样的:

<span th:text="${#locale.country}">Should give you Country (in my case HR)</span> 
<span th:text="${#ctx.locale}">Should give you the code (in my case hr_HR)</span>
<span th:text="${#locale.country}=='ar' ? 'Arabic' : 'Not Arabic'"></span>

or maybe better like this:

或者像这样更好:

<span th:text="${#strings.startsWith(#ctx.locale, 'ar')? 'Arabic' : 'Not Arabic'}></span>

since java provides 17 different codes for arabic, and they all start with ar, last example should work on all...

由于 java 为阿拉伯语提供了 17 种不同的代码,并且它们都以 ar 开头,因此最后一个示例应该适用于所有...

I believe you would know how to use it in your javascript.

我相信你会知道如何在你的 javascript 中使用它。

PS> More information you can find in Apendix A.

PS> 您可以在附录 A 中找到更多信息