Thymeleaf Study Notes-Basics (Chinese course)

Source: Internet
Author: User
Tags utext

Turn from:

Http://www.cnblogs.com/vinphy/p/4674247.html

(a) What is a Thymeleaf?

Simply put, Thymeleaf is a template engine similar to Velocity and Freemarker, which can completely replace JSP. Compared with other template engines, it has the following three attractive features: 1.Thymeleaf in a network and no network environment can be run, that is, it can let the artist in the browser to view the static effect of the page, but also allows programmers to view the server with Data dynamic page effect. This is because it supports HTML prototypes, and then adds additional attributes to the HTML tag to show how the template + data is presented.    When the browser interprets HTML, the undefined label attribute is ignored, so the thymeleaf template can be run statically, and when data is returned to the page, the thymeleaf tag dynamically replaces the static content, making the page dynamic. 2.Thymeleaf out-of-the-box features. It provides standard and spring standard dialect, can directly apply the template to achieve jstl, OGNL expression effect, avoid the daily set of templates, the Jstl, change the label of the puzzle.    Developers can also expand and create custom dialects. 3. Thymeleaf provides a spring standard dialect and an optional module that is perfectly integrated with the SPRINGMVC, enabling quick implementation of form bindings, attribute editors, and internationalization. (ii) Application 1. Simple Thymeleaf Application 1) just add Thymeleaf-2.1.4.release.jar (http://www.thymeleaf.org/download.html) package, if using MAVEN, Add the following configuration
<dependency>    <groupId>org.thymeleaf</groupId>    <artifactid>thymeleaf</ Artifactid>    <version>2.1.4</version></dependency>
2) then add the header file (below)
<! DOCTYPE html>

3) You can dynamically replace the static data with th tag. For example, an outgoing message in the background will replace the static data "red Chair", and if you visit a static page, the data "Red Chair" is displayed.

<TD th:text= "${message}" >red chair</td>

2. Integrate Spring

1) Add Thymeleaf-spring4-2.1.4.release.jar (http://www.thymeleaf.org/download.html) package, if using MAVEN, add the following configuration

<dependency>    <groupId>org.thymeleaf</groupId>    <artifactid>thymeleaf-spring3 </artifactId>    <version>2.1.4</version></dependency>

2) Add the following code to the servlet configuration file

<!--Scans The classpath of this application for @Components to deploy as beans-to-<context:component-scan       Base-package= "Com.test.thymeleaf.controller"/> <!--configures the @Controller programming model-- <mvc:annotation-driven/> <!--resolves view names to protected. JSP resources within The/web-inf/views Directory--<!--springmvc+jsp's jump page configuration-<!--<bean class= "Org.springframework.web.servlet.vie W.internalresourceviewresolver ">--> <!--<property name=" prefix "value="/web-inf/views/"/&GT;--&G              T <!--<property name= "suffix" value= ". jsp"/>--> <!--</bean>--> <!--Springmvc+thymele AF Jump Page configuration--<bean id= "Templateresolver" class= "org.thymeleaf.templateresolver.ServletContextTemplate Resolver "> <property name=" prefix "value="/web-inf/views/"/> <property name=" suffix "value=". HTML "/&Gt <property name= "Templatemode" value= "HTML5"/> </bean> <bean id= "Templateengine" Clas s= "Org.thymeleaf.spring4.SpringTemplateEngine" > <property name= "templateresolver" ref= "Templateresolver"/&       Gt </bean> <bean class= "Org.thymeleaf.spring4.view.ThymeleafViewResolver" > <property name= "Templ Ateengine "ref=" Templateengine "/> </bean>

3) Add the static page to the project, change the file header, add the th tag.

3.th Label Finishing

1) Simple expression

--Variable expression ${...}

<input type= "text" name= "UserName" value= "James Carrot" th:value= "${user.name}"/>

The preceding code refers to the Name property value that references the user object.

--Select/Asterisk expression *{...}

<div th:object= "${session.user}" >                                                                            <p>nationality: <span th:text= "*{nationality}" >Saturn< /span>.</p>    </div>

The selection expression is typically followed by the Th:object, which takes the attributes in the object directly.

--Text internationalization expression #{...}

<p th:utext= "#{home.welcome}" >welcome to our grocery store!</p>

Call the Internationalized Welcome statement, and the internationalized resource file is as follows

Resource_en_us.properties:
Home.welcome=welcome to here!
Resource_zh_cn.properties:

Home.welcome= Welcome to your arrival!

--URL expression @{...}

<a href= "details.html" th:href= "@{/order/details (Orderid=${o.id})}" >view</a>
@{......} Supports decision paths and relative paths.   The relative path also supports cross-context invocation of URLs and protocol references (//code.jquery.com/jquery-2.0.3.min.js). When the URL is a background outgoing parameter, the code is as follows

2) Common th tags

--Simple data conversion (numeric, date)

<dt> Price </dt>  <dd th:text= "${#numbers. Formatdecimal (Product.price, 1, 2)}" >180</dd> < dt> Purchase Date </dt> <dd th:text= "${#dates. Format (product.availablefrom, ' Yyyy-mm-dd ')}" >2014-12-01</dd >

--string concatenation

<dd th:text= "${' $ ' +product.price}" >235</dd>

--escaped and non-escaped text

When the data is sent back in the background as "this was an &lt;em&gt; Html&lt;/em&gt; Text. &lt;b&gt; Enjoy yourself!&lt;/b&gt; " , there are two different results if the page code

<div th:text= "${html}" >
This was an &lt;em&gt; Html&lt;/em&gt; Text. &lt;b&gt; Enjoy yourself!&lt;/b&gt;

<div th:utext= "${html}" >
This was an <em>HTML</em> text. <b>enjoy yourself!</b>
</div>

--In the form

<form th:action= "@{/bb}" th:object= "${user}" method= "POST" th:method= "POST" >    <input type= "text" th: Field= "*{name}"/>    <input type= "text" th:field= "*{msg}"/>    <input type= "Submit"/></form >

--Show the data iteration of the page

Using Th:remove to remove static data except for the first one, iterate through the first TR tag to display <tbody th:remove= "All-but-first" >//Set the productlist in the background Row iterations, received with the product parameter, access to property values via product <tr th:each= "Product:${productlist}" >
            Statistics with count, sequential display &LT;TD th:text= "${productstat.count}" >1</td> <td th:text= "${product.description}" >red chair</td> <td th:text= "${' $ ' + #numbers. Formatdecima L (Product.price, 1, 2)} ">$123</td> <td th:text=" ${#dates. Format (product.availablefrom, ' yyy Y-mm-dd ')} ">2014-12-01</td> </tr> <tr> <td>whi Te table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> <tr> <td>reb table</td> <t d>$200</td> <td>15-Jul-2013</td> </tr> <tr& Gt <td>blue table</td> <td>$200</td> <td>15-jul-2013</ TD> </tr> </tbody>

--Conditional judgment

<span th:if= "${product.price LT" class= "offer" >special offer!</span>

Can not use "<", ">" and other symbols, to use "LT" and other alternatives

<!--when gender exists, select the corresponding option, and if gender does not exist or is null, obtain the NAME--><TD th:switch= "${customer.gender" of the Customer object. Name ()} ">     <!--use"/images/male.png "image--    < IMG th:case= "' FEMALE '" src= ". /.. /.. /images/female.png "th:src=" @{/images/female.png} "alt=" female "/> <!--use"/images/female.png "image--    <span th:case= "*" >Unknown</span></td>
<!--appear first on the page, and then modify the data that is displayed--
<div class= "Form-group col-lg-6" >
<label> name <span>&nbsp;</span></label>
<! --Unless the Name property value of the Resume object is null, the value of name is used as the placeholder value--
<input type= "text" class= "Form-control" th:unless= "${resumes.name} eq" or ${resumes.name} EQ null "
Data-required= "true" th:placeholder= "${resumes.name}"/>
<!--unless the Name property of the Resume object is not empty, define a field to encapsulate the object easily and use placeholder to prompt-

Data-required= "true" th:placeholder= "please fill in your real name" />
</div>
<!--add class= "enhanced" when balance heavy rain 10000--><td th:class= "${customer.balance GT 10000}? ' Enhanced ' "th:text=" ${customer.balance} ">350</td>

--Select Select option based on background data

<div class= "Form-group col-lg-6" >      <label > Sex <span>&nbsp; sex:</span></label>      <select th:field= "${resume.gender}" class= "Form-control" th:switch= "${ Resumes.gender.toString ()} "            data-required=" true ">              <option value=" male "th:case=" ' Male ' "th:selected=" Selected "> Male </option>              <option value=" female "th:case=" ' Female ' "th:selected=" selected "> Women </option>              <option value= "" > Please select </option>      </select> </div>

Because gender is a defined enum (enum) type, use the ToString method. Specify the outgoing variable with Th:switch, and match the value of the variable with th:case. "Please select" Put in the first item will appear always selected is this option. or with Th:if.

<div class= ' Form-group col-lg-4 ' >          <select class= ' form-control ' name= ' skill[4].proficiency ' >                <option > Mastery </option>                <option th:if= "${skill.level eq" General '} "th:selected=" selected "> General </ option>                 <option th:if= "${skill.level eq ' proficiency '}" th:selected= "selected" > Proficiency </option>                 < Option th:if= "${skill.level eq ' proficient '}" th:selected= "selected" > Proficient </option>           </select></div>

--spring Expression Language

<! DOCTYPE html>

--Inline

<label for= "Body" >message body:</label><textarea id= "body" name= "body" th:inline= "text" >dear [[${ Customername}]],it is we sincere pleasure to congratulate your in your birthday:    Happy birthday [[${customername}]]!! ! See you soon, [[${customername}]]. Regards, the    Thymeleaf team</textarea>

--inline JS <js start and end add the following code, otherwise the quotation marks are nested or "<" ">" cannot be used >

/*<! [cdata[*/....../*]]>*/

--js Additional code:

/*[+var msg = ' This is a working application '; +]*/

--js Remove Code:

/*[-*/var msg = ' This is a non-working template ';/*-]*/

4. Infrequently used

--An expression

2) Text

            a) text text                     &NB Sp   ' One text ', ' Another one ',......             B) Digital text           &NBSP ;            0,34,3.0,12.3,......            C) Boolean text     &N Bsp                  true,flase            D) empty text &n Bsp                          null            e) text Mark                         One,sometext,main ,......        3) Text processing             a) string connection                       +            B) text replacement         &N Bsp &nbSp               | The name ID ${name} |                4) arithmetic expressions             a) basic expressions   &NB Sp                    +,-,*,/,%            B) Minus (unary operator)          -        5) Boolean expression             A) Basic expressions                        and,or      &NB Sp     B) Boolean negation (unary operator)    ! ,not        6) comparison and equality             a) comparison           & nbsp                    >,<,>=,<= (gt,lt,ge,le)    &nbs P           B) Equality expressions                       = = ,! = (Eq,ne) &nbsp       7) Conditional expressions              a) if-then           & nbsp                 (IF)? (then)              b) if-then-else               &NBS P     (IF)? (then): (else)              c) Default                           (value)? : (defaltvalue)                       All these tags can be combined and nested:  &nbs P           user is of type ' + (${user.isadmin ()}? ' Administrator ': (${user.type}?: ' Unknown '))

--Expression Base Object

        Some object expressions have greater flexibility when evaluating OGNL expressions in context variables. These objects will be referenced by the # number.        -  #ctx: Context object .       -  #vars:  context variable .      & nbsp -  #locale: Contextual locale .       -  #httpServletRequest: (only on the web) httpservletrequest  objects.        -  #httpSession: (Web only)  HttpSession  object .     --expression feature object        -  #dates: A practical way to java.util.Date objects.         -  #calendars: Similar to dates, but  java.util.Calendar  object .       -  #numbers: A practical way to format numeric objects.        -  #strings: A practical approach to character creation:  contains, StartsWith, prepending/appending .       -  #objects: A Practical approach to objects operations.        -  #bools: A practical way to evaluate Boolean values.        -  #arrays: An array of practical methods.        -  #lists: A practical way to list.        -  #sets: A practical method for set.        -  #maps: A practical way to map.        -  #aggregates: A practical way to create aggregations on arrays or collections.        -  #messages: A practical way to get external information in an expression.        -  #ids: A practical way to handle potentially duplicate ID attributes (for example, the result of an iteration).      --set a value for a specific property         The following is an action set value with Th:action.            <form action= "subscribe.html" th:action= "@{/subscribe}" >        There are many such attributes, each of which is specific to a particular XHTML or HTML5 property:            th:text= "${data}" & nbsp                to replace the value of data with the body of the label that contains the attribute. Character constants are quoted, such as th:text= "' Hello World '", th:text= "2011+3", th:text= "' My Name is ' +${user.name} '
The difference between Th:utext and Th:text is "unescaped text".
Th:with defines variables, th:with= "iseven=${prodstat.count}%2==0", and defines multiple variables that can be separated by commas.
Th:attr set tag Properties, multiple properties can be separated by commas, such as th:attr= "[Email Protected]{/image/aa.jpg},title=#{logo}", this label is not very elegant, generally used less.
TH:[TAGATTR] Set various properties of the label, such as Th:value,th:action.
You can set two properties at a time, for example: th:alt-title= "#{logo}"
Add prefixes and suffixes to attributes, using th:attrappend,th:attrprepend, such as: th:attrappend= "class=${" +cssstyle} "
For attributes that have certain values, such as the Checked property, the thymeleaf takes a bool value, such as Th:checked=${user.isactive}
Th:each Loop, <tr th:each= "User,userstat:${users}" >,userstat is a state variable with index,count,size,current,even,odd,f Irst,last Properties, if no setting state variable is displayed, Thymeleaf defaults to a state variable named "Variable name +stat".
Th:if or th:unless conditions, supports Boolean values, numbers (nonzero is true), characters, strings, and so on.
Th:switch,th:case the SELECT statement. Th:case= "*" indicates the default case.

Thymeleaf Study Notes-Basics (Chinese course)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.