Using Thymeleaf 3.0.9, suppose I have this translation:
hello=Hello {0}
In my template, I have:
<span th:text="#{hello(${user.getName()})}"></span>
Now suppose user.getName() can be null, so I want to display something nice in that case:
<span th:text="#{hello(${user.getName()?:'Unknown'})}"></span>
This works fine.
Now I also want to tranlate Unknown, how can I do this?
I tried:
<span th:text="#{hello(${user.getName()?:#{unknown})}"></span>
But that does not seem to work.
I think you can use the #messages utility object:
<span th:text="#{hello(${user.getName()?:#messages.msg('unknown')})}"></span>
And add property in the messages file(s):
unknown=Unknown
Related
I have my messages.properties like this:
tablas.menu.paises=Pa\u00EDses
tablas.menu.regiones=Regiones
tablas.menu.anhos=A\u00F1os
tablas.menu.universidades=Universidades
tablas.menu.usuarios=Usuarios
In the .html I have a menu showing each item with th:each:
<li class="nav-item" th:each="menu : ${menus}">
<a th:text="#{tablas.menu.${menu.nombre}}"></a>
</li>
For each "menu in ${menus}", menu.nombre has the values paises, regiones, anhos...
But thymeleaf doesn't recognise the model variable inside the #{}, and this it is giving me in the view the error when it doesn't find the message:
??tablas.menu.${menu.nombre}_es_ES??
Configuration is ok, if I change the call for #{tablas.menu.regiones} I get 'regiones' and so.
Is there any way to call a message from messages.properties dynamically using a model variable like this?
Thanks.
You can use the #messages utility object for this:
<a th:text="${#messages.msg('tablas.menu.' + menu.nombre)}" />
Or you can create the string using literal substitution:
<a th:text="#{|tablas.menu.${menu.nombre}|}" />
I would recommend using preprocessing only as a last resort, as bad values can cause runtime errors. (Although they do work for this.)
I have problem with thymleaf spring boot, my input is like this
<input class="-Text" type="text" style="border:none" placeholder="1234567890xx" th:value="${sn}" name="sn"/>
I want to get parse the value from input to my th href thymleaf code like this
<a id="btnx" th:href="#{/pages/input-order-manual/finish-confirm/?sn=__${sn}__}" class="btn btn-primary btn-lg btn-block">Confirm</a>
But when I try to run, this value always return null for my sn variable, what must I do, to make this code run?
For any help,
Thank you in advance
Insert full code. Run code in debug, add break point before return template and make sure you have sn variable in model. Also you can concat th:href (th:href="#{/pages/input-order-manual/finish-confirm/?} + ${sn}")
I would like to use Bootstrap's has-success and has-failure classes with Thymeleaf.
So far I have
<div th:class="${#fields.hasErrors('field')}? 'form-group has-error' : 'form-group'"></div>
This displays the failure style correctly, when the form is posted and the field is invalid.
However if I change the second part of the ternary to 'form-group has-success', then on the initial form GET request, then, of course, it styles it as a success, even though the form hasn't been posted yet.
My question: is there a way in Thymeleaf to handle the following
Displays a form without any styling on GET.
On POST apply has-error or has-success classes.
I think you'll need to add attributes to your Model in the back-end for this.
In you GET request, change nothing. In your POST request, add an attribute: ["hasErrors", true] if the form data you send via the post is incorrect, false otherwise.
Now in your html you can add the following:
<th:block th:if="${hasErrors != null}">
<div th:class="${hasErrors ? 'form-group has-error' : 'form-group has success'"></div>
</th:block>
<th:block th:unless="${hasErrors != null}">
<div class="form-group"></div>
</th:block>
You check if the hasErrors model attribute isn't null, if it is, it means you're in the GET method and you should display a simple form-group. If the hasErrors is not null, you can create the ternary expression based on the boolean value hasErrors. The th:block is non-html. You can replace it with a div, but then you neen an extra div just to check a boolean.
I'm not going into GET/POST problem but I think that this can help you:
New th:errorclass for adding CSS class to form fields in error
Until now, whenever we wanted to apply a specific CSS class to an input field in a form when there were errors for that field, we needed to use the th:class or th:classappend attributes.
In Thymeleaf 2.1, in order to simplify this structure, a new th:errorclass attribute processor has been introduced. This processor will read the name of the field from the name or th:field attribute in the same tag, and apply the specified class if such field has errors.
Note the 'error' literal is in fact a token, so no single quotes are really needed.
The result is much more concise. Note also that th:errorclass works like th:classappend, not th:class. So the specified class will in fact be appended to any existing ones.
http://www.thymeleaf.org/whatsnew21.html#errcl
I found that Thymeleaf as a hasAnyErrors function.
<div class="form-group row"
th:attrappend="class=${#fields.hasAnyErrors()
? #fields.hasErrors('field') ? ' has-error' : ' has-success'
: '' }">
This now works.
When the user GETs the form, hasAnyErrors is false, so the empty string is appended and the input and label receive the default style.
When the user POSTs the form, if there are any errors then the first part of the ternary is evaluated. This adds the has-error or has-success styles.
This was inspired by Roel Strolenberg's answer below.
I am working on a Spring MVC application that uses Thymeleaf as template engine and I am trying to capitalize some string showed into my page. On my page I have something like this:
<li class="com__nav-item" th:each="menuItem : ${#authentication.principal.listaFunzioniUtente}">
<a href="" class="com__nav-link centered">
<span class="blue-line animate scaleIn delay-3" style="font-size: 1.4em; text-align: center;" th:text="${#strings.capitalize(menuItem.desFnz)}"></span>
<span class="white-circle animate scaleIn delay-5"></span>
</a>
</li>
As you can see in the previous code, in the first <span> tag, I show a string inside the desFnz property of the menuItem object.
It works fine, my problem is that I want capitalize all the characters, so I tried to do:
th:text="${#strings.capitalize(menuItem.desFnz)}"
using the #strings.capitalize() but it can't work, in fact in my page I still obtain the text but not capitalized. Why? What am I missing? How can I fix this issue?
#strings.capitalize(menuItem.desFnz) will only capitalize the 1st character, where as #strings.toUpperCase(menuItem.desFnz) will convert the entire string to uppercase. Here is the documentation for the Strings class.
you can do it by
$string.toLowerCase() or $string.toUpperCase()
Just adding to Pradeep Pati's point.
In case you are using it in the spring boot project where some of your values are coming from messages.properties
like In messages.properties file, You have something like:
email.dailyAlert.greeting.newTemplate = Dear {0},
Then to substitute the value in place of {0} (in the Title case), you need to write like the below line.
<p th:text="#{email.dailyAlert.greeting.newTemplate(${#strings.capitalize(orgSlug)})}"></p>
The final output will be:
Dear Organisation,
Currently I'm getting some data from the database and after that I want to render it within my Blade template.
In my queried data I have blade functions like url('/foo') combined with some html. And here is the problem.
When I'm using {!! $child->description !!} the HTML is rendered correctly, but my Blade function won't work:
Function: url('/foo)
Output: http://myurl.de/url('/foo')
When I'm using the "normal" Syntax like {{ $child->description }} the generated URL is correct (http://myurl.de/foo), but the HTML is not rendered.
So my question is:
How can I use my queried Blade function within rendered HTML? ^^
/Edit
Okay, perhaps my question is too abstract. So I want to show you my problem based on my example. (generated template image - only on german, sorry)
Every form is a database entry like:
categoryName
categoryParent
...
categoryDescription
As you can see on my image, the categoryDescription is the small text under my first input field with the small button.
I want to use this script abstract as possible so that I can fill the entry with every content I want to fill in.
In this case my content is:
lore ipsum <a class="btn btn-primary btn-sm pull-right" href="url('foo')">dolor</a>
As you can see there is the mentioned Blade-function (url) and the HTML.
{!! !!} - this dont escapse string so if u have something from database like,
something it would output it like that.
While in other hand {{ }} this would give you just "something" without , it is used to protect you from injections.
Maybe blade error.{{}}
lore ipsum <a class="btn btn-primary btn-sm pull-right" href="{{url('foo')}}">dolor</a>
Laravel Blade