How to Use ES6 Template Literals in Freemarker? [duplicate] - javascript

I'm trying to use Freemarker in conjunction with jQuery Templates.
Both frameworks use dollar sign/curly brackets to identify expressions for substitution (or as they're called in freemarker, "interpolations") , e.g. ${person.name} .
So when I define a jQuery Template with expressions in that syntax, Freemarker tries to interpret them (and fails).
I've tried various combinations of escaping the ${ sequence to pass it through Freemarker to no avail - \${, \$\{, $\{, etc.
Inserting a freemarker comment in between the dollar and the curly (e.g. $<#-- -->{expression}) DOES work - but I'm looking for a more concise and elegant solution.
Is there a simpler way to get a Freemarker template to output the character sequence ${?

This should print ${person.name}:
${r"${person.name}"}
From the freemarker docs
A special kind of string literals is the raw string literals. In raw string literals, backslash and ${ have no special meaning, they are considered as plain characters. To indicate that a string literal is a raw string literal, you have to put an r directly before the opening quotation mark or apostrophe-quote

For longer sections without FreeMarker markup, use <#noparse>...</#noparse>.
Starting with FreeMarker 2.3.28, configure FreeMarker to use square bracket syntax ([=exp]) instead of brace syntax (${exp}) by setting the interpolation_syntax configuration option to square_bracket.
Note that unlike the tag syntax, the interpolation syntax cannot be specified inside the template. Changing the interpolation syntax requires calling the Java API:
Configuration cfg;
// ...
cfg.setInterpolationSyntax(SQUARE_BRACKET_INTERPOLATION_SYNTAX);
Then FreeMarker will consider ${exp} to be static text.
Do not confuse interpolation syntax with tag syntax, which also can have square_bracket value, but is independent of the interpolation syntax.
When using FreeMarker-based file PreProcessor (FMPP), either configure the setting via config.fmpp or on the command-line, such as:
fmpp --verbose --interpolation-syntax squareBracket ...
This will call the appropriate Java API prior to processing the file.
See also:
https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html
http://fmpp.sourceforge.net/settings.html#templateSyntax

Another option is to use #include with parse=false option. That is, put your jQuery Templates into the separate include page and use parse=false so that freemarker doesn't try and parse it.
This would be a good option when the templates are larger and contain double quotes.

I had to spent some time to figure out the following scenarios to escape ${expression} -
In Freemarker assignment:
<#assign var = r"${expression}">
In html attribute:
Some link
In Freemarker concatenation:
<#assign x = "something&"+r"${expression}"/>

If ${ is your only problem, then you could use the alternate syntax in the jQuery Templates plugin like this: {{= person.name}}
Maybe a little cleaner than escaping it.

Did you try $$?
I found from the Freemarker manual that ${r"${person.name}"} will print out ${person.name} without attempting to render it.
Perhaps you should also take a look at Freemarker escaping freemarker

I can confirm that the
${r"${item.id}"}
is the correct way as an example.
So I kinda full example will look like
<span> Remove </span>
and the output will be :
<span> Remove </span>

In the case when you want to use non-raw strings so that you can escape double quotes, apostrophes, etc, you can do the following:
Imagine that you want to use the string ${Hello}-"My friend's friend" inside of a string. You cannot do that with raw strings. What I have used that works is:
${"\x0024{Hello}-\"My friend's friend\""}
I have not escaped the apostrophe since I used double quotes.

Related

Convert JavaScript string to JavaScript literal

In Chrome, when you right-click a string on the console, you'll see "copy string as javascript literal" option. This is what I want to have now, in JavaScript.
For example, let's say I have the following text content:
console.log('hoge');
My question is, how can I get something below from the above?
"console.log('hoge');"
I want to do this because, I have a mega bytes of webpack-generated long JavaScript content, and for a reason I need to eval() the script on an other environment, so I want to copy-and-paste the JavaScript literal text to inside the "eval()". (you may suggest exchanging the data not with the literal but with json (json.stringify/parse), I know, but I just prefer the literal way for now)
So is it possible? Thanks.
After noting the advice regarding the security weakness inherent in using eval (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)
You can achieve what you want by enclosing the entire literal code inside back-ticks and using the resulting string as the eval argument. back tick quotted strings can include line breaks so you should be able to pass your entire code block inside a single set.
Working snippet.
console.log('hoge');
console.log('another hoge');
eval(`console.log('hoge');
console.log('another hoge')`);
You can easily enclose Javascript in backticks to get a template literal:
eval(`console.log('hoge')`)
But you should also escape backticks inside the Javascript code to handle situations like this:
eval(`console.log(`hoge`)`) // SyntaxError
As a solution, you can use this bash one-liner:
sed 's/`/\\`/g' | xargs -0 printf 'eval(`%s`)'
Invoke the command by pressing Enter.
Paste in the Javascript you want to escape and press Enter again.
Press Ctrl+D to finish input.
You will get valid eval() function call with escaped template literal on the output.
You can assign this one-liner command to an alias for easy use:
alias js_eval_literal="sed '"'s/`/\\`/g'"' | xargs -0 printf '"'eval(`%s`)'"'"

Passing a multiline string as parameter to js function

When calling displayBarNotification(stringIPass, 'success', 3500) of nopcommerce originally defined in public.common.js seems the call fails when stringIPass contains newlines.
The error on the client-side was something like
Unexpected line break in a string literal
I tried replacing the C# newline character in the ajax function to the js equivalent and it worked. However, I intend to keep the "newlines" for readability reasons. What approach would you suggest?
Pardon me for the lack of the exact error expr. but it's because I'm currently not at work. I will update tomorrow if necessary.
Official documentation:
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Use back-ticks ( ` ) to introduce a template literal:
var example = `
this
is
a
test
`;
console.log(example);

Template Strings Without Variable Interpolation

Is it possible to have a template string in JavaScript that does not interpolate the variable values? I would like to have actual JS code blocks (which will be multi-line and contain escape sequences) like this example:
...
return String.raw`console.log(\`Here is my code:\n\n ${code}\`);`
that I can pass between functions in my Node.js app. I have no problem escaping backticks but I'd like to know if there's an easy way to stop interpolation of the variables so that I can have template strings nested inside of my template string.
I know that one option is to define code as let code = '${code}'; but I was wondering if there was a cleaner way to do it where interpolation was completely turned off in the same way that String.raw turns off interpretation of escape sequences.

Does typescript/javascript have a #"\" equivalent like C#?

Is there a way that I can put slashes in a string in javascript without having to put two?
In C# I could do this:
#"This\is not used as an escape\"
(The # in front of the string makes it not use \ as an escape char.)
Is there something like this in javascript/typescript?
No, there is not this kind of escaping in javascript
String literals
The # is called a verbatim string in C#. One of the key objectives is to allow you have strings that are multiline.
To get the same effect you use a template string in TypeScript / JavaScript : https://basarat.gitbooks.io/typescript/content/docs/template-strings.html
However you would still need to escape any usages of \. 🌹

Do the single quote (') and double quote (") work in jQuery like they do in PHP?

Does either the single quote (') or double quote (") have a function where they will parse through the string and replace variables with values? I remember that in PHP the parsing engine will parse through the string and automatically switch out any variables with their values (I don't remember which actually has that effect off the top of my head) so you don't have to type "somestring" + aVariableusing the concatenation
operator. in what I have read through so far on http://www.tutorialspoint.com/jquery/jquery-basics.htm I haven't been able to find anything about it. Also unless I missed it the post When to use double or single quotes in JavaScript? does not directly cover this information.
Single quotes and double quotes are identical in JavaScript and do not interpolate variables. In my experience it's good practise to stick with single quotes in JS, allowing you to use double quotes inside those strings (without escaping) for things like HTML attributes.
However, ES2015 introduced "template strings" using backticks, which are somewhat like PHP's strings in that they can interpolate into a string, and are if anything more powerful because they'll actually interpolate any expression, not just plain variables:
let bar = 'bar';
let foo = `${bar}`;
let FOO = `${bar.toUpperCase()}`;
No, there is no such thing as variable interpolation in JavaScript (and therefore jQuery)
And that's a very good thing! While PHP has all variables identified by $ at the start, JavaScript does not. So even a simple string such as "Hello world!" could go horribly wrong if you had a variable called world...
You may be interested in a templating system, of which there are many options out there - a quick Google search will turn up results, but here's a list of some with examples and stuff.

Categories

Resources