Various JS templates; Why two {? - javascript

I'm puzzled by this notation that did spread a lot after the first templating engine using it became successful. The notation is {{bla}}
Does anyone know the practical reason for having two sets of {}? I think it reads very poorly; The deprecated JQuery one made more sense ( ${bla} )

It's because it's not an often used combination of characters.
Template parsing is all about regular expressions and then turning the text into tokens, and then compiling those tokens into another language (like HTML).
Since we don't want to catch common characters in our regular expressions, we need to use those that aren't common combos of characters.
it's the same reason PHP uses <?php ?> and ASP uses <% %>.
Like in Twig, the lexer looks for {{ }} and {% %} to find Twig commands. If I had to use { }, every time I had that anywhere in the template (not just HTML markup), I'd have to escape it. And since the point of a template language is ease of use, The language needs to make its "tokens" as distinguishable as possible.

How come Distal works without needing any escape characters like {{}}? http://code.google.com/p/distal

Related

Are there drawbacks to using backticks for all string operations in Typescript? [duplicate]

Is there a reason (performance or other) not to use backtick template literal syntax for all strings in a javascript source file? If so, what?
Should I prefer this:
var str1 = 'this is a string';
over this?
var str2 = `this is another string`;
Code-wise, there is no specific disadvantage. JS engines are smart enough to not have performance differences between a string literal and a template literal without variables.
In fact, I might even argue that it is good to always use template literals:
You can already use single quotes or double quotes to make strings. Choosing which one is largely arbitrary, and you just stick with one. However, it is encouraged to use the other quote if your string contains your chosen string marker, i.e. if you chose ', you would still do "don't argue" instead of 'don\'t argue'. However, backticks are very rare in normal language and strings, so you would actually more rarely have to either use another string literal syntax or use escape codes, which is good.
For example, you'd be forced to use escape sequences to have the string she said: "Don't do this!" with either double or single quotes, but you wouldn't have to when using backticks.
You don't have to convert if you want to use a variable in the string in the future.
However, those are very weak advantages. But still more than none, so I would mainly use template literals.
A real but in my opinion ignorable objection is the one of having to support environments where string literals are not supported. If you have those, you would know and wouldn't be asking this question.
The most significant reason not to use them is that ES6 is not supported in all environments.
Of course that might not affect you at all, but still: YAGNI. Don't use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single quotes in JavaScript? carry over as well. As always, keep your code base consistent and use only one string literal style where you don't need a special one.
Always use template literals. In this case YAGNI is not correct. You absolutely will need it. At some point, you will have add a variable or new line to your string, at which point you will either need to change single quotes to backticks, or use the dreaded '+'.
Be careful when the values are for external use. We work with Tealium for marketing analysis, and it currently does not support ES6 template literals. Event data containing template literals aka string templates will cause the Tealium script to error.
I'm fairly convinced by other answers that there's no serious downside to using them exclusively, but one additional counterpoint is that template strings are also used in advanced "tagged template" syntax, and as illustrated in this Reddit comment, if you try to rely exclusively on JavaScript's automatic semicolon insertion or just forget to include a semicolon, you can run into parsing issues with statements that begin with a template string.
// OK (single (or double) quotes)
logger = console.log
'123'.split('').forEach(logger)
// OK (semicolon)
logger = console.log;
`123`.split('').forEach(logger)
// Not OK
logger = console.log
`123`.split('').forEach(logger) // Error

Encoding/Decoding Javascript in Nashorn

I use the technique described here:
http://scriptasylum.com/tutorials/encode-decode.html
In a nutshell, one has a javascript file that looks like this, where the actual javascript is encoded:
document.write( unescape( 'escaped string' ) ); dF('encoded javascript');
I now want to run that same .js module under Nashorn, but Nashorn does not have a document object. Therefore, I can not do document.write().
Note: It is well known that this technique is easily bypassed and people modest technical ability can still look at the actual code. My use case does not require strong security so that is not a concern. That said, Please consider answers on why one should not do this as off topic. Thanks.
Basically, that code breaks down into two parts:
Un-obfuscate the string via unescape.
Write the string out via document.write.
It sounds like you want to use the string directly for some reason.
You have at least two options:
You can provide a document object to the scripting engine with a write method that accepts a string. Then you can do with it what you like. (Or substitute document.write before evaluating the string with any function you want called.)
Remove the document.write( and the corresponding ) at the end and have the engine evaluate the string and hand it to you directly as the result of ScriptEngine#eval.
Either way, you'll end up with a string that you can then do something with.

Is JavaScript/ECMAScript a Regular Language?

I've tried a few google searches, and I cannot come up with any articles/previous questions that address this. The reason is a minor dispute I'm having with someone about using input validation to reject possible XSS. I know for a fact that HTML isn't a regular language, but I can't make that argument quite as strongly for javascript.
I checked this link:
http://www.dlsi.ua.es/~mlf/nnafmc/pbook/node46.html
And I've come up with this: Since tags in html can be infinitely nested, that's an intuitive notion as to why HTML is NOT a regular language. By extension, since you can infinitely nest blocks of JavaScript code with {}, then javascript too is NOT a regular language.
I'd like to see a more formal presentation either for or against this informal proposition. Or maybe even a discussion about regex extensions in programming languages that perhaps make it possible to do this kind of thing without writing a parser.
Indeed, JavaScript is not a regular language, which can be proved with the fact that braces must be balanced as your intuition suggested.
A useful tool for demonstrating that languages are not regular is the Pumping Lemma. You can use it to demonstrate that if JavaScript was regular, some sequence like
function(){ function() { function(){ ... function () {
(in which { are not matched) could be repeated any number of times when surrounded by a certain prefix and suffix, which is in obviously in contradiction with the fact that curly braces must be matched.

Most basic javascript templating solution...?

I am looking to create a variable that is a template for repatative elements of my site. I however am only using it infrequently so I do not wish to use a javascript templating engine or library.
I am using jquery... if that effects anyones approach.
This is one of my templates.
$html_template = json_encode("
var html = '<a href=\"javascript:ajax(\'#content\',\'{$conf['dir']['web_url']}profile.php?user_id='+data.id+'\');\">
<div id=\"'+data.id+'\" class=\"fb_user\">
<img alt=\"'+data.name+'\" height=\"50\" width=\"50\" />
<p>
'+data.first_name+'
<br/>
'+data.last_name+'
</p>
</div>';");
I have gotten so lost in escaping I can't work out where I have gone wrong. The plan is to use eval within the templating function to replace the variables.
Hope someone can help
Use an editor with good highlighting and you will see where to escape.
The apostrophes (') that are inside the javascript code shouldn't be escaped, use double backslash (\) instead, so the javascript will see a single backslash and therefore will escape the apostrophe.
In the anchor don't use javascript code as href, use "#" for link and add onClick="...".
I don't think "ajax" is a jQuery function, perhaps you meant "$.ajax", but it has different parameters, may be you should read its manual.
Try to implement it in pure html and js before writing it in php and you'll know where to escape (after it works in first place).

Best way to generate javascript code in ruby (RoR)

I have seen some rails plugins which generate javascript code dynamically using ruby.
1.
%Q ( mixed block of javascript and ruby )
2.
<<-CODE
some mixed ruby and javascript code
CODE
Being a java developer I don't understand
what those strange looking syntax mean ?
Is one way better than the other ?
can anyone point me to proper documentation about such things ?
The first syntax is Ruby's string literal syntax. Specifically, the %Q (capital Q as opposed to lower-case) means that the string will be interpolated. eg:
%Q[Here's a string with #{a_variable} interpolated!]
Note that you can use any arbitrary characters as the open and close delimiters.
The second syntax is Ruby's heredoc syntax. The dash after the opening << indicates that Ruby will strip whitespace from the beginning of input lines contained in the heredoc block.
Ruby on Rails ships with the Prototype JavaScript framework built-in already. It also ships with JS generator helper methods which generate the Prototype code dynamically based on Ruby code.
You needn't use these if you don't want to. In fact, I rarely use them or Prototype at all, as jQuery is my JS framework of choice. So one way is not "better" than the other (except in the general sense that heredoc is better than the string literal syntax for certain cases).
In Ruby %Q provides a double quote delimited string, so:
%Q(mixed block of javascript and ruby) #=> "mixed block of javascript and ruby"
<<-CODE is what Ruby calls a Here Document, or simply heredoc. This is a mechanism for creating free format strings whilst preserving special characters such as new lines and tabs.
A heredoc is created by preceding the text with << followed by the delimiter string you wish to use to mark the end of the text.
text = <<-DOC
To be, or not to be: that is the question
William Shakespeare
DOC
When this string is printed it appears exactly as it was entered, together with all the new lines and tabs:
To be, or not to be: that is the question
William Shakespeare
%Q is the equivalent to a "" string in Ruby. But if you use such %Q-syntax, you don't need to escape double quotes.
It's a HEREDOC declaration. You also don't need to escape quotes there.
Strings in Ruby.
Here you can find the details.
Ruby with javascript

Categories

Resources