简体   繁体   中英

Line break in JEXL String

I'm using JEXL in Java in standard way:

var script = new JexlBuilder().create().createScript(jexlScript);
var jexlContext = new MapContext(); 
var returnString = (String) script.execute(jexlContext));

Let's say that jexScript looks like:

var paramA = 'AAAA';
var paramB = 'BBBB';
var command = paramA + '\n' + paramB;
return command;

Output is:

AAAA\nBBBB

My question is: How to introduce new line char to properly format this text? Or any other way to get new line separation in String creating in Jexl.

I'm new to Apache JEXL, but I've found these ways:

1. Use multi-line strings

var paramA = 'AAAA';
var paramB = 'BBBB';
var command = `${paramA}
${paramB}`;
return command;

The literal newline in the multi-line string format (delimited with backticks) will be preserved. Use variable substitution to bring in your other variables.

2. Use the context to inject newline as a variable

In your Java code, populate the context:

var jexlContext = new MapContext(); 
jexlContext.set("newline", "\n");

Then use it in your script:

var paramA = 'AAAA';
var paramB = 'BBBB';
var command = paramA + newline + paramB;
return command;

3. Use Java-style Unicode escapes

This is a feature that existed but was undocumented prior to version 3.2 ( JEXL-331 ). You can use a Java-style Unicode escape inside a string literal. The hexadecimal value of \\n is 0x0a, so use:

var command = paramA + '\u000a' + paramB;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM