Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace Variables with issue as empty String #998

Open
rider87 opened this issue Feb 24, 2024 · 1 comment
Open

Replace Variables with issue as empty String #998

rider87 opened this issue Feb 24, 2024 · 1 comment

Comments

@rider87
Copy link

rider87 commented Feb 24, 2024

Hi,

I have a HTML Text, which will have some Thymeleaf variables.
If I have some unknown variables etc. I will get always an error message an the String will not replace with variables anymore.
I would like to replace the values for which I got an error just with an empty String ("").
How can I do this?

Here a simple test: customer. (with dot) is an issue for Thymeleaf, therefore I will get an error.

`public static void main(String[] args) {

	StringTemplateResolver templateResolver = new StringTemplateResolver();
	templateResolver.setTemplateMode(TemplateMode.HTML);

	// Erstelle eine Template-Engine
	TemplateEngine templateEngine = new TemplateEngine();
	templateEngine.setTemplateResolver(templateResolver);

	String templateString = "<p>Hello, {{customer.name}} !</p>";

	Customer customer = new Customer();
	customer.setName("Meier");

	Context context = new Context();
	context.setVariable("customer.", customer);

	templateString = replaceCustomVariableSyntax(templateString);

	// Prozessiere das Template mit den Variablen
	StringWriter stringWriter = new StringWriter();

	try {
		templateEngine.process(templateString, context, stringWriter);
	} catch (Exception e) {
		// Catch any exceptions and return an empty string
	}

	System.out.println(stringWriter.toString());
}

`

Any ideas?

@duoduobingbing
Copy link

duoduobingbing commented Mar 18, 2024

I do not know if I understand your problem correctly but as this setup is using OGNL please make sure to include the adequate dependency of ognl:ognl (for Thymeleaf 3.1.2 its OGNL 3.3.4)

It is unclear what your replaceCustomVariableSyntax(templateString); method does but I guess it replaces the {{customer.name}} with something OGNL can handle like [[${customer.name}]] so that the final template string looks something like <p>Hello, [[${customer.name}]] !</p>

When you add customer. as a variable, there is no customer, thus the lookup of customer.name in your template fails with a null pointer exception. If you want an empty string, just use safe navigation:

<p>Hello, [[${customer} ? ${customer.name}]] !</p>

This will succeed even when customer is not set in the context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants