Issue
I am using Spring Boot with Thymeleaf, and I'm passing the post object to the view resolver. I only want to display a certain portion of the post.content field, meaning something like this
example:
This is the column from the database.
____
---------------
content column
---------------
text text text t
ext text text
---------------
So I want to display only a certain number of characters in the .html page like here:
Your text: text text te... 'read more'
I have tried
<p id="postcontent" th:utext="${#strings.substring(${post.content},0,12)}"></p>
However, I get a template parsing error and then I tried
<p id="postcontent" th:utext="${#strings.substring(post.content,0,12)}"></p>
This just prints the whole content of the expression.
L.E So, I found the correct syntax which is
th:utext="${#strings.substring(post.content,0,17)}"
The issue now is that, if the string is smaller than the desired length, I get a
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: 17
Is there a way to fix this? Lets say this will never happen because there will never be a post content with such a short length, but I want to have a way to manage this exception.
Solution
To understand your error, you have to know what strings are.
Strings in java are arrays of char:
char[] example = {'H', 'E', 'L', 'L', 'O');
You can manipulate strings in a similar why to arrays. Arrays first index is 0 and max Index length - 1
Let now assume the above example is an instance of String and you do:
example.subString (0, 3) // Return value would be "HEL".
example.subString (0, 10) // StringIndexOutOfBoundsException
To prevent this, you have to use whats ever come first. Your cap at 17 or the cap defined by the length of the string.
example.subString (0, Math.min(17, example.length()));
While there is no built in function in Thymeleaf, you can use the special T(...) operator to call static methods (allowing you to use Java's Math.max(...) in your Thymeleaf).
<div th:with="maxNumber=${T(Math).min(8,12)}">
<p th:text=${maxNumber}></p>
</div>
As mentioned in the comments, there is a more Thymeleaf special method to approach your goal:
I want to abbreviate a string with Thymeleaf
Answered By - Marcinek
Answer Checked By - Mildred Charles (JavaFixing Admin)