Convert line feed code to html line feed tag with Thymeleaf and output

Even if Thymeleaf outputs a character string including line breaks with th: text etc., the line breaks are not reflected on the screen. It is necessary to convert the line feed code to the \
tag.

environment

point

Implementation

There are two methods, so I will introduce them.

① Implemented on View

Use only existing Thymeleaf syntax. You don't need to set it in advance, so you can use it easily.

<th:block th:if="${sentence}">
    <th:block th:each="str, stat : ${sentence.split('\r\n|\r|\n', -1)}">
        <th:block th:text="${str}"/>
        <br th:if="${!stat.last}"/>
    </th:block>
</th:block>

Divide the character you want to output by the line feed code and loop with th: each. The contents are output as th: text, and \
is inserted between them.

② Define your own dialect

The above implementation is easy, but it becomes complicated when used in multiple places. Therefore, create your own dialect so that you can refer to it from View.

__Conversion processing and text output processor __

TextLineProcessor.java


import org.thymeleaf.Arguments;
import org.thymeleaf.Configuration;
import org.thymeleaf.dom.Element;
import org.thymeleaf.processor.attr.AbstractUnescapedTextChildModifierAttrProcessor;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressionExecutionContext;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.unbescape.html.HtmlEscape;


/**
 *Processor that converts line feed code to br tag
 */
public class TextLineProcessor extends AbstractUnescapedTextChildModifierAttrProcessor {

    public static final int ATTR_PRECEDENCE = 1450;
    public static final String ATTR_NAME = "textbr";


    protected TextLineProcessor() {
        super(ATTR_NAME);
    }


    @Override
    public int getPrecedence() {
        return ATTR_PRECEDENCE;
    }


    /**
     *Returns the output string
     *
     * @param arguments
     * @param element
     * @param attributeName
     * @return
     */
    @Override
    protected final String getText(
            final Arguments arguments, final Element element, final String attributeName) {

        String text = getAttributeObjectString(arguments, element, attributeName);

        //html escape processing
        text = HtmlEscape.escapeHtml4Xml(text);

        //Replace line feed code with br tag
        return text.replaceAll("\r\n|\r|\n", "<br/>");
    }


    /**
     *Get the variable specified in the attribute as a character string
     *
     * @param arguments
     * @param element
     * @param attributeName
     * @return
     */
    protected String getAttributeObjectString(
            final Arguments arguments, final Element element, final String attributeName) {

        final String attributeValue = element.getAttributeValue(attributeName);

        final Configuration configuration = arguments.getConfiguration();
        final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(configuration);

        final IStandardExpression expression = expressionParser.parseExpression(configuration, arguments, attributeValue);

        final Object result =
                expression.execute(configuration, arguments, StandardExpressionExecutionContext.UNESCAPED_EXPRESSION);

        return (result == null ? "" : result.toString());

    }
}

Implemented by referring to the processing of th: text and th: utext. To briefly explain the process ...

  1. Escape processing of html tag
  2. Replace line feed code with \
    tag
  3. Screen output without escaping it

__ Dialect registration __ Register the created processor in the dialect.

CustomDialect.java


import org.thymeleaf.dialect.AbstractDialect;
import org.thymeleaf.processor.IProcessor;

import java.util.HashSet;
import java.util.Set;


/**
 *Register your own defined dialect
 */
public class CustomDialect extends AbstractDialect{

    static final String DIALECT_PREFIX = "ex";

    @Override
    public String getPrefix() {
        return DIALECT_PREFIX;
    }


    @Override
    public Set<IProcessor> getProcessors() {
        final Set<IProcessor> processors = new HashSet<IProcessor>();
        processors.add(new TextLineProcessor());
        return processors;
    }
}

__Thymeleaf settings __

ThymeleafConfiguration.java


import com.ushidatmhr.thymeleaf.CustomDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ThymeleafConfiguration {

    @Bean
    CustomDialect myDialect() {
        return new CustomDialect();
    }

}

__ How to use __

<p ex:textbr="${sentence}" />

Recommended Posts

Convert line feed code to html line feed tag with Thymeleaf and output
Create your own dialect to convert line feed code to line feed tag in Thymeleaf3
How to specify character code and line feed code in JAXB
How to set character code and line feed code in Eclipse
Convert Markdown to HTML with flexmark-java
Convert JSON to TSV and TSV to JSON with Ruby
How to embed JavaScript variables in HTML with Thymeleaf
I tried to read and output CSV with Outsystems
Until INSERT and SELECT to Postgres with Spring boot and thymeleaf
Sample code to parse date and time with Java SimpleDateFormat
Convert Excel to Blob with java, save it, read it from DB and output it as a file!
HTML was made into a common part with Thymeleaf to unify the design and improve development efficiency.
Collect line feed codes with enum
Writing code with classes and instances
How to convert LocalDate and Timestamp
Output PDF and TIFF with Java 8
[Android] Convert Android Java code to Kotlin
[Java: memorandum] Until the line feed code CRLF is changed to LF