Thymeleaf用法大全转载

Thymeleaf用法大全

2018-09-20 16:04:29 wszhlzjl 阅读数 4680

  • Thymeleaf语法

    在自己使用Thymeleaf语法时,我非常希望有一篇很全的Thymeleaf语法的总结,但很可惜没有找到,总是零零散散。贴上官方链接(比较长):Thymeleaf官方说明文档 。现 全面总结 如下:


    1. 基本表达式

    (1) 变量的表达式:${...}
    用于访问 容器上下文环境 中的变量,例:


    <span th:text="${information}">
     

    (2) 选择变量表达式:*{...}
    选择表达式计算的是 选定的对象 (th:object对象属性绑定的对象)


    <div th:object="${session. user}" >
    Name: <span th: text=" *{firstName}" >Sebastian.
    Surname: <span th: text=" *{lastName}" >Pepper.
    Nationality: <span th: text=" *{nationality}" >Saturn.
    </div>
     

    (3) 信息表达式:#{...}
    一般用于 显示页面静态文本。将可能需要根据需求而整体变动的静态文本放在properties文件中,方便维护。通常与th:text属性一起使用。例如:
    新建/WEB-INF/templates/home.html,段落:


    <p th: text=" #{home. welcome}" >This text will not be show!
     

    新建/WEB-INF/templates/home.properties,home.welcome:


    home.welcome=this messages is from home.properties!
     

    显示效果为:


    Spring Boot总结(9)---Thymeleaf用法大全_Java
    显示效果

    (4) 链接URL表达式:@{...}
    用于链接。可以链接目录下的静态资源,也可以链接到后端请求处理接口,如:


    <link th:src="@{/resources/css/bootstrap.min.css}" />
    <li><a th:href="@{/forIndex}">首页</a></li>
     

    (5) 工具对象表达式#maps
    常用于 日期、集合、数组对象的访问 。这些工具对象就像是java对象,可以访问对应java对象的方法来进行各种操作。


    <div th:if="${#maps.size(stu)!=0}">
    ...do something...
    </div>
     

    常用的对象表达式总结如下:


    #dates: java.util的实用方法。对象:日期格式、组件提取等.
    #calendars: 类似于#日期,但对于java.util。日历对象
    #numbers: 格式化数字对象的实用方法。
    #strings:字符串对象的实用方法:包含startsWith,将/附加等。
    #objects: 实用方法的对象。
    #bools: 布尔评价的实用方法。
    #arrays: 数组的实用方法。
    #lists: list集合。
    #sets:set集合。
    #maps: map集合。
    #aggregates: 实用程序方法用于创建聚集在数组或集合.
    #messages: 实用程序方法获取外部信息内部变量表达式,以同样的方式,因为他们将获得使用# {…}语法
    #ids: 实用程序方法来处理可能重复的id属性(例如,由于迭代)。
    #httpServletRequest:用于web应用中获取request请求的参数
    #session:用于web应用中获取session的参数
     

    具体用法代码示例如下,可自行ctrl+F搜索寻找自己需要的:


    Dates
    #dates : utility methods for java.util.Date objects:
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Dates
    * ======================================================================
    */
    /*
    * Null-safe toString()
    */
    ${#strings.toString(obj)} // also array*, list* and set*
    /*
    * Format date with the standard locale format
    * Also works with arrays, lists or sets
    */
    ${#dates.format(date)}
    ${#dates.arrayFormat(datesArray)}
    ${#dates.listFormat(datesList)}
    ${#dates.setFormat(datesSet)}
    /*
    * Format date with the specified pattern
    * Also works with arrays, lists or sets
    */
    ${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
    ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
    ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
    ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
    /*
    * Obtain date properties
    * Also works with arrays, lists or sets
    */
    ${#dates.day(date)} // also arrayDay(...), listDay(...), etc.
    ${#dates.month(date)} // also arrayMonth(...), listMonth(...), etc.
    ${#dates.monthName(date)} // also arrayMonthName(...), listMonthName(...), etc.
    ${#dates.monthNameShort(date)} // also arrayMonthNameShort(...), listMonthNameShort(...), etc.
    ${#dates.year(date)} // also arrayYear(...), listYear(...), etc.
    ${#dates.dayOfWeek(date)} // also arrayDayOfWeek(...), listDayOfWeek(...), etc.
    ${#dates.dayOfWeekName(date)} // also arrayDayOfWeekName(...), listDayOfWeekName(...), etc.
    ${#dates.dayOfWeekNameShort(date)} // also arrayDayOfWeekNameShort(...), listDayOfWeekNameShort(...), etc.
    ${#dates.hour(date)} // also arrayHour(...), listHour(...), etc.
    ${#dates.minute(date)} // also arrayMinute(...), listMinute(...), etc.
    ${#dates.second(date)} // also arraySecond(...), listSecond(...), etc.
    ${#dates.millisecond(date)} // also arrayMillisecond(...), listMillisecond(...), etc.
    /*
    * Create date (java.util.Date) objects from its components
    */
    ${#dates.create(year,month,day)}
    ${#dates.create(year,month,day,hour,minute)}
    ${#dates.create(year,month,day,hour,minute,second)}
    ${#dates.create(year,month,day,hour,minute,second,millisecond)}
    /*
    * Create a date (java.util.Date) object for the current date and time
    */
    ${#dates.createNow()}
    /*
    * Create a date (java.util.Date) object for the current date (time set to 00:00)
    */
    ${#dates.createToday()}
    Calendars
    #calendars : analogous to #dates, but for java.util.Calendar objects:
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Calendars
    * ======================================================================
    */
    /*
    * Format calendar with the standard locale format
    * Also works with arrays, lists or sets
    */
    ${#calendars.format(cal)}
    ${#calendars.arrayFormat(calArray)}
    ${#calendars.listFormat(calList)}
    ${#calendars.setFormat(calSet)}
    /*
    * Format calendar with the specified pattern
    * Also works with arrays, lists or sets
    */
    ${#calendars.format(cal, 'dd/MMM/yyyy HH:mm')}
    ${#calendars.arrayFormat(calArray, 'dd/MMM/yyyy HH:mm')}
    ${#calendars.listFormat(calList, 'dd/MMM/yyyy HH:mm')}
    ${#calendars.setFormat(calSet, 'dd/MMM/yyyy HH:mm')}
    /*
    * Obtain calendar properties
    * Also works with arrays, lists or sets
    */
    ${#calendars.day(date)} // also arrayDay(...), listDay(...), etc.
    ${#calendars.month(date)} // also arrayMonth(...), listMonth(...), etc.
    ${#calendars.monthName(date)} // also arrayMonthName(...), listMonthName(...), etc.
    ${#calendars.monthNameShort(date)} // also arrayMonthNameShort(...), listMonthNameShort(...), etc.
    ${#calendars.year(date)} // also arrayYear(...), listYear(...), etc.
    ${#calendars.dayOfWeek(date)} // also arrayDayOfWeek(...), listDayOfWeek(...), etc.
    ${#calendars.dayOfWeekName(date)} // also arrayDayOfWeekName(...), listDayOfWeekName(...), etc.
    ${#calendars.dayOfWeekNameShort(date)} // also arrayDayOfWeekNameShort(...), listDayOfWeekNameShort(...), etc.
    ${#calendars.hour(date)} // also arrayHour(...), listHour(...), etc.
    ${#calendars.minute(date)} // also arrayMinute(...), listMinute(...), etc.
    ${#calendars.second(date)} // also arraySecond(...), listSecond(...), etc.
    ${#calendars.millisecond(date)} // also arrayMillisecond(...), listMillisecond(...), etc.
    /*
    * Create calendar (java.util.Calendar) objects from its components
    */
    ${#calendars.create(year,month,day)}
    ${#calendars.create(year,month,day,hour,minute)}
    ${#calendars.create(year,month,day,hour,minute,second)}
    ${#calendars.create(year,month,day,hour,minute,second,millisecond)}
    /*
    * Create a calendar (java.util.Calendar) object for the current date and time
    */
    ${#calendars.createNow()}
    /*
    * Create a calendar (java.util.Calendar) object for the current date (time set to 00:00)
    */
    ${#calendars.createToday()}
    Numbers
    #numbers : utility methods for number objects:
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Numbers
    * ======================================================================
    */
    /*
    * ==========================
    * Formatting integer numbers
    * ==========================
    */
    /*
    * Set minimum integer digits.
    * Also works with arrays, lists or sets
    */
    ${#numbers.formatInteger(num,3)}
    ${#numbers.arrayFormatInteger(numArray,3)}
    ${#numbers.listFormatInteger(numList,3)}
    ${#numbers.setFormatInteger(numSet,3)}

    /*
    * Set minimum integer digits and thousands separator:
    * 'POINT', 'COMMA', 'NONE' or 'DEFAULT' (by locale).
    * Also works with arrays, lists or sets
    */
    ${#numbers.formatInteger(num,3,'POINT')}
    ${#numbers.arrayFormatInteger(numArray,3,'POINT')}
    ${#numbers.listFormatInteger(numList,3,'POINT')}
    ${#numbers.setFormatInteger(numSet,3,'POINT')}

    /*
    * ==========================
    * Formatting decimal numbers
    * ==========================
    */
    /*
    * Set minimum integer digits and (exact) decimal digits.
    * Also works with arrays, lists or sets
    */
    ${#numbers.formatDecimal(num,3,2)}
    ${#numbers.arrayFormatDecimal(numArray,3,2)}
    ${#numbers.listFormatDecimal(numList,3,2)}
    ${#numbers.setFormatDecimal(numSet,3,2)}
    /*
    * Set minimum integer digits and (exact) decimal digits, and also decimal separator.
    * Also works with arrays, lists or sets
    */
    ${#numbers.formatDecimal(num,3,2,'COMMA')}
    ${#numbers.arrayFormatDecimal(numArray,3,2,'COMMA')}
    ${#numbers.listFormatDecimal(numList,3,2,'COMMA')}
    ${#numbers.setFormatDecimal(numSet,3,2,'COMMA')}
    /*
    * Set minimum integer digits and (exact) decimal digits, and also thousands and
    * decimal separator.
    * Also works with arrays, lists or sets
    */
    ${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}
    ${#numbers.arrayFormatDecimal(numArray,3,'POINT',2,'COMMA')}
    ${#numbers.listFormatDecimal(numList,3,'POINT',2,'COMMA')}
    ${#numbers.setFormatDecimal(numSet,3,'POINT',2,'COMMA')}

    /*
    * ==========================
    * Utility methods
    * ==========================
    */
    /*
    * Create a sequence (array) of integer numbers going
    * from x to y
    */
    ${#numbers.sequence(from,to)}
    ${#numbers.sequence(from,to,step)}
    Strings
    #strings : utility methods for String objects:
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Strings
    * ======================================================================
    */
    /*
    * Check whether a String is empty (or null). Performs a trim() operation before check
    * Also works with arrays, lists or sets
    */
    ${#strings.isEmpty(name)}
    ${#strings.arrayIsEmpty(nameArr)}
    ${#strings.listIsEmpty(nameList)}
    ${#strings.setIsEmpty(nameSet)}
    /*
    * Perform an 'isEmpty()' check on a string and return it if false, defaulting to
    * another specified string if true.
    * Also works with arrays, lists or sets
    */
    ${#strings.defaultString(text,default)}
    ${#strings.arrayDefaultString(textArr,default)}
    ${#strings.listDefaultString(textList,default)}
    ${#strings.setDefaultString(textSet,default)}
    /*
    * Check whether a fragment is contained in a String
    * Also works with arrays, lists or sets
    */
    ${#strings.contains(name,'ez')} // also array*, list* and set*
    ${#strings.containsIgnoreCase(name,'ez')} // also array*, list* and set*
    /*
    * Check whether a String starts or ends with a fragment
    * Also works with arrays, lists or sets
    */
    ${#strings.startsWith(name,'Don')} // also array*, list* and set*
    ${#strings.endsWith(name,endingFragment)} // also array*, list* and set*
    /*
    * Substring-related operations
    * Also works with arrays, lists or sets
    */
    ${#strings.indexOf(name,frag)} // also array*, list* and set*
    ${#strings.substring(name,3,5)} // also array*, list* and set*
    ${#strings.substringAfter(name,prefix)} // also array*, list* and set*
    ${#strings.substringBefore(name,suffix)} // also array*, list* and set*
    ${#strings.replace(name,'las','ler')} // also array*, list* and set*
    /*
    * Append and prepend
    * Also works with arrays, lists or sets
    */
    ${#strings.prepend(str,prefix)} // also array*, list* and set*
    ${#strings.append(str,suffix)} // also array*, list* and set*
    /*
    * Change case
    * Also works with arrays, lists or sets
    */
    ${#strings.toUpperCase(name)} // also array*, list* and set*
    ${#strings.toLowerCase(name)} // also array*, list* and set*
    /*
    * Split and join
    */
    ${#strings.arrayJoin(namesArray,',')}
    ${#strings.listJoin(namesList,',')}
    ${#strings.setJoin(namesSet,',')}
    ${#strings.arraySplit(namesStr,',')} // returns String[]
    ${#strings.listSplit(namesStr,',')} // returns List<String>
    ${#strings.setSplit(namesStr,',')} // returns Set<String>
    /*
    * Trim
    * Also works with arrays, lists or sets
    */
    ${#strings.trim(str)} // also array*, list* and set*
    /*
    * Compute length
    * Also works with arrays, lists or sets
    */
    ${#strings.length(str)} // also array*, list* and set*
    /*
    * Abbreviate text making it have a maximum size of n. If text is bigger, it
    * will be clipped and finished in "..."
    * Also works with arrays, lists or sets
    */
    ${#strings.abbreviate(str,10)} // also array*, list* and set*
    /*
    * Convert the first character to upper-case (and vice-versa)
    */
    ${#strings.capitalize(str)} // also array*, list* and set*
    ${#strings.unCapitalize(str)} // also array*, list* and set*
    /*
    * Convert the first character of every word to upper-case
    */
    ${#strings.capitalizeWords(str)} // also array*, list* and set*
    ${#strings.capitalizeWords(str,delimiters)} // also array*, list* and set*
    /*
    * Escape the string
    */
    ${#strings.escapeXml(str)} // also array*, list* and set*
    ${#strings.escapeJava(str)} // also array*, list* and set*
    ${#strings.escapeJavaScript(str)} // also array*, list* and set*
    ${#strings.unescapeJava(str)} // also array*, list* and set*
    ${#strings.unescapeJavaScript(str)} // also array*, list* and set*
    /*
    * Null-safe comparison and concatenation
    */
    ${#strings.equals(str)}
    ${#strings.equalsIgnoreCase(str)}
    ${#strings.concat(str)}
    ${#strings.concatReplaceNulls(str)}
    /*
    * Random
    */
    ${#strings.randomAlphanumeric(count)}
    Objects
    #objects : utility methods for objects in general
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Objects
    * ======================================================================
    */
    /*
    * Return obj if it is not null, and default otherwise
    * Also works with arrays, lists or sets
    */
    ${#objects.nullSafe(obj,default)}
    ${#objects.arrayNullSafe(objArray,default)}
    ${#objects.listNullSafe(objList,default)}
    ${#objects.setNullSafe(objSet,default)}
    Booleans
    #bools : utility methods for boolean evaluation
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Bools
    * ======================================================================
    */
    /*
    * Evaluate a condition in the same way that it would be evaluated in a th:if tag
    * (see conditional evaluation chapter afterwards).
    * Also works with arrays, lists or sets
    */
    ${#bools.isTrue(obj)}
    ${#bools.arrayIsTrue(objArray)}
    ${#bools.listIsTrue(objList)}
    ${#bools.setIsTrue(objSet)}
    /*
    * Evaluate with negation
    * Also works with arrays, lists or sets
    */
    ${#bools.isFalse(cond)}
    ${#bools.arrayIsFalse(condArray)}
    ${#bools.listIsFalse(condList)}
    ${#bools.setIsFalse(condSet)}
    /*
    * Evaluate and apply AND operator
    * Receive an array, a list or a set as parameter
    */
    ${#bools.arrayAnd(condArray)}
    ${#bools.listAnd(condList)}
    ${#bools.setAnd(condSet)}
    /*
    * Evaluate and apply OR operator
    * Receive an array, a list or a set as parameter
    */
    ${#bools.arrayOr(condArray)}
    ${#bools.listOr(condList)}
    ${#bools.setOr(condSet)}
    Arrays
    #arrays : utility methods for arrays
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Arrays
    * ======================================================================
    */
    /*
    * Converts to array, trying to infer array component class.
    * Note that if resulting array is empty, or if the elements
    * of the target object are not all of the same class,
    * this method will return Object[].
    */
    ${#arrays.toArray(object)}
    /*
    * Convert to arrays of the specified component class.
    */
    ${#arrays.toStringArray(object)}
    ${#arrays.toIntegerArray(object)}
    ${#arrays.toLongArray(object)}
    ${#arrays.toDoubleArray(object)}
    ${#arrays.toFloatArray(object)}
    ${#arrays.toBooleanArray(object)}
    /*
    * Compute length
    */
    ${#arrays.length(array)}
    /*
    * Check whether array is empty
    */
    ${#arrays.isEmpty(array)}
    /*
    * Check if element or elements are contained in array
    */
    ${#arrays.contains(array, element)}
    ${#arrays.containsAll(array, elements)}
    Lists
    #lists : utility methods for lists
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Lists
    * ======================================================================
    */
    /*
    * Converts to list
    */
    ${#lists.toList(object)}
    /*
    * Compute size
    */
    ${#lists.size(list)}
    /*
    * Check whether list is empty
    */
    ${#lists.isEmpty(list)}
    /*
    * Check if element or elements are contained in list
    */
    ${#lists.contains(list, element)}
    ${#lists.containsAll(list, elements)}
    /*
    * Sort a copy of the given list. The members of the list must implement
    * comparable or you must define a comparator.
    */
    ${#lists.sort(list)}
    ${#lists.sort(list, comparator)}
    Sets
    #sets : utility methods for sets
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Sets
    * ======================================================================
    */
    /*
    * Converts to set
    */
    ${#sets.toSet(object)}
    /*
    * Compute size
    */
    ${#sets.size(set)}
    /*
    * Check whether set is empty
    */
    ${#sets.isEmpty(set)}
    /*
    * Check if element or elements are contained in set
    */
    ${#sets.contains(set, element)}
    ${#sets.containsAll(set, elements)}
    Maps
    #maps : utility methods for maps
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Maps
    * ======================================================================
    */
    /*
    * Compute size
    */
    ${#maps.size(map)}
    /*
    * Check whether map is empty
    */
    ${#maps.isEmpty(map)}
    /*
    * Check if key/s or value/s are contained in maps
    */
    ${#maps.containsKey(map, key)}
    ${#maps.containsAllKeys(map, keys)}
    ${#maps.containsValue(map, value)}
    ${#maps.containsAllValues(map, value)}
    Aggregates
    #aggregates : utility methods for creating aggregates on arrays or collections
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Aggregates
    * ======================================================================
    */
    /*
    * Compute sum. Returns null if array or collection is empty
    */
    ${#aggregates.sum(array)}
    ${#aggregates.sum(collection)}
    /*
    * Compute average. Returns null if array or collection is empty
    */
    ${#aggregates.avg(array)}
    ${#aggregates.avg(collection)}
    Messages
    #messages : utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{...} syntax.
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Messages
    * ======================================================================
    */
    /*
    * Obtain externalized messages. Can receive a single key, a key plus arguments,
    * or an array/list/set of keys (in which case it will return an array/list/set of
    * externalized messages).
    * If a message is not found, a default message (like '??msgKey??') is returned.
    */
    ${#messages.msg('msgKey')}
    ${#messages.msg('msgKey', param1)}
    ${#messages.msg('msgKey', param1, param2)}
    ${#messages.msg('msgKey', param1, param2, param3)}
    ${#messages.msgWithParams('msgKey', new Object[] {param1, param2, param3, param4})}
    ${#messages.arrayMsg(messageKeyArray)}
    ${#messages.listMsg(messageKeyList)}
    ${#messages.setMsg(messageKeySet)}
    /*
    * Obtain externalized messages or null. Null is returned instead of a default
    * message if a message for the specified key is not found.
    */
    ${#messages.msgOrNull('msgKey')}
    ${#messages.msgOrNull('msgKey', param1)}
    ${#messages.msgOrNull('msgKey', param1, param2)}
    ${#messages.msgOrNull('msgKey', param1, param2, param3)}
    ${#messages.msgOrNullWithParams('msgKey', new Object[] {param1, param2, param3, param4})}
    ${#messages.arrayMsgOrNull(messageKeyArray)}
    ${#messages.listMsgOrNull(messageKeyList)}
    ${#messages.setMsgOrNull(messageKeySet)}
    IDs
    #ids : utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
    /*
    * ======================================================================
    * See javadoc API for class org.thymeleaf.expression.Ids
    * ======================================================================
    */
    /*
    * Normally used in th:id attributes, for appending a counter to the id attribute value
    * so that it remains unique even when involved in an iteration process.
    */
    ${#ids.seq('someId')}
    /*
    * Normally used in th:for attributes in <label> tags, so that these labels can refer to Ids
    * generated by means if the #ids.seq(...) function.
    *
    * Depending on whether the <label> goes before or after the element with the #ids.seq(...)
    * function, the "next" (label goes before "seq") or the "prev" function (label goes after
    * "seq") function should be called.
    */
    ${#ids.next('someId')}
    ${#ids.prev('someId')}
    Request
    <p th:text="${#httpServletRequest.getParameter('q')}" >Test
    Session
    <div th:text="${session.xx}">[...]</div>

    2. 常用属性

    Thymeleaf语法的使用,都是通过在html页面的标签中添加th:xx关键字来实现模板套用,且其属性与html页面标签基本类似。常用属性有:


    th:action 表单提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
    th:each 属性赋值 <tr th:each="user,userStat:${users}">
    th:field 常用于表单字段绑定 <input type="text" value="" th:field="*{username}"></input>
    th:href 链接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
    th:id 替换id <input th:id="'xxx' + ${collect.id}"/>
    th:if 判断条件 <a th:if="${userId == collect.userId}" >
    th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
    th:fragment 布局标签,定义代码片段,其它引用 <div th:fragment="alert">
    th:object 替换对象 <div th:object="${session.user}">
    th:src 图片类地址引入 ![](@{/img/logo.png})
    th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div>
    th:text 文本替换 <p th:text="${collect.description}">description
    th:value 属性赋值 <input th:value="${user.name}" />
    th:inline 定义js脚本可以使用变量 <script type="text/javascript" th:inline="javascript">
    th:remove 删除某个属性 <tr th:remove="all">
    th:style 设置样式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
    th:onclick 点击事件 th:οnclick="'getCollect()'"
     

    (1) th:action:
    定义后台控制器路径,类似<form>标签的action属性。例如:


    <form th:action="@{/login}">...</form>
     

    (2) th:each:
    对象遍历,功能类似jsp中的<c:forEach>标签。用于遍历展示或者遍历录入。例如:


    <form th:action="@{/addStudent}"
    th:object="${stuReqBean}" method="POST">
    <div th:each="stuIter,rowStat:${stuReqBean.students}">
    <input type="text" value=""
    th:field="*{students[__${rowStat.index}__].firstName}"></input>
    <input type="text" value=""
    th:field="*{students[__${rowStat.index}__].school}"></input>
    ...
    </div>
    </form>

    //后台代码
    @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
    public String addStudent(@ModelAttribute(value = "stuReqBean")
    StudentRequestBean stuReqBean,ModelMap model) {...}
     

    (3) th:field:
    常用于表单字段绑定。通常与th:object一起使用。 属性绑定、集合绑定。


    <form th:action="@{/login}" th:object="${loginBean}">...
    <input type="text" value="" th:field="*{username}"></input>
    <input type="text" value="" th:field="*{user[0].username}"></input>
    </form>
     

    (4) th:href:
    定义超链接,类似<a>标签的href 属性。value形式为@{/logout}


    <a th:href="@{/logout}"></a>
     

    (5) th:id:
    div id声明,类似html标签中的id属性。


    <div th:id = "stu+(${rowStat.index}+1)"></div>
     

    (6) th:if:
    条件判断。如果为否则标签不显示,例如:


    <div th:if="${rowStat.index} == 0">... do something ...</div>
     

    (7) th:include&;th:fragment:
    声明定义该属性的div为模板片段,常用与头文件、页尾文件的引入。常与th:include,th:replace一起使用。
    声明模板片段/WEBINF/templates/footer. html :


    <div th: fragment=" copy" >
    © 2011 The Good Thymes Virtual Grocery
    </div>
     

    引入模板片段:


    <div th: include=" /templates/footer : : copy" ></div>
    <div th: replace=" /templates/footer : : copy" ></div>
    </div>
     

    (8) th:object:
    用于表单数据对象绑定,将表单绑定到后台controller的一个JavaBean参数。常与th:field一起使用进行表单数据绑定。


    public class LoginBean implements Serializable{...}

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@ModelAttribute(value = "loginBean") LoginBean loginBean,ModelMap model) {...}

    <form th:action="@{/login}" th:object="${loginBean}">...</form>
     

    (9) th:src:
    用于外部资源引入,类似于<script>标签的src属性,常与@{}一起使用。


    <script th:src="@{/resources/js/jquery/jquery.json-2.4.min.js}"
     

    (10) th:text:
    文本显示。


    <td th:text="${username}" ></td>
     

    (11) th:value:
    用于标签复制,类似<option>标签的value属性。


    <option th:value="Adult">Adult</option>
    <input type="hidden" th:value="${msg}" />
     

    (12) th:inline:
    定义js脚本可以使用变量。


    <script th:inline="javascript">
    //提交表单
    function form_submit() {
    var data={
    userId:[[${userId}]], //js引用后端传来的值
    role:[[${role}]],
    password:$("#password").val(),
    }
    $.post("xx",data,function (mes) {
    ...xxx...
    })
     

    (12) th:remove:
    用于移除标签。


    <a th:remove="${status}!=0?all:none" >未提交</a>
     

    (13) th: style:
    用于修改标签style。


    <span th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''">
     

    (14) th: onclick:
    用于修改点击事件。


    <button th:οnclick="'getCollect()'"></button>

    3. 标准表达式

    (1) 字面
    文本文字:放在 单引号 里面,可以是任意字符,如:'one text','Another one!',...


    <span th:text="'working web application'">template file
     

    数字文字:0,34,3.0,12.3,...


    <span th:text="2013">1492
     

    布尔文字:true,false


    <div th:if="${user.isAdmin()} == false">
     

    空字面: null


    <div th:if="${variable.something} == null">
     

    (2) 文字操作:

     

    字符串连接: +


    <span th:text="'Welcome to our application, ' + ${user.name} + '!'">
     

    文字替代: |The name is ${name}|


    <span th:text="|Welcome to our application, ${user.name}!|">
     

    (3) 算术运算:
    二元运算符:+,-,*,/,%


    <span th:text="1+1">1+1
     

    (4) 布尔运算:
    二元运算符:and,or
    布尔否定(一元运算符): !,not


    <span th:if="${!#lists.isEmpty(list)} and ${#lists.isEmpty(list)}" >and
    <span th:if="${!#lists.isEmpty(list)} or ${#lists.isEmpty(list)}" >or
    <span th:if="${!#lists.isEmpty(list)}">not
     

    (5) 比较和相等:
    比较:>,<,>=,<=(gt,lt,ge,le)
    相等判断:==,!=(eq,ne)


    <ol>
    <li>>(gt):<span th:text="1+1" th:if="${#lists.size(list)} > 1">大于>else</li>
    <li>小于lt:<span th:if="${#lists.size(list)} lt 1">小于else</li>
    <li>>=(ge):<span th:if="${#lists.size(list)} >= 1">大于等于>=else</li>
    <li>小于等于(le):<span th:if="${#lists.size(list)} le 1">小于等于else</li>
    <li>!(not):<span th:if="${!#lists.isEmpty(list)}">!(not)else</li>
    <li>==(eq):<span th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')">等于==</li>
    <li>!=(ne/neq):size:<span th:text="${#lists.size(list)}" th:if="${#lists.size(list)} != 1"></li>
    </ol>
     

    (6) 条件运算符:
    IF-THEN: (if) ? (then)


    <span th:class="${title1} ? 'green'">样例
     

    IF-THEN-ELSE: (if) ? (then) : (else)


    <span th:class="${title} ? 'green' :' red'">样例一
     

    默认: (value) ?: (defaultvalue)


    <span th:text="*{age}?: '(no age specified)'">20
     

    至此,Thymeleaf的语法用法已经基本描述完毕。详细阅读此篇,可以让大家在使用Thymeleaf模板引擎时事半功倍。

     

     

    贴几个很好的Thymeleaf总结参考博客,这些博主都写得很好。本文部分内容摘录自这些博客。
    雪山上的蒲公英---Thymeleaf
    ITPSC---Thymeleaf
    指尖舞步---Thymeleaf

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值