How do I interpolate variable string in pug? - javascript

In the following, myVar contains the string "Today, it's the ${date}".
Furthermore, there is an variable with the name date that contains "1st of October". I expect the following pug syntax to replace the literal ${date} with the date variable content.
span!= myVar
Unfortunately, the example results in
<span>Today, it's the ${date}</span>
Expected result:
<span>Today, it's the 1st of October.</span>
Best regards,
Benedikt

Yes, exactly as #omgninjas pointed out, it is called interpolation and preceded by # in Pug.
However you can't always use it (eg. inside a string). Here are some examples:
sensor is a variable passed by the controller to the view.
Normal interpolation. Works as expected:
<div id=#{sensor} style="width:90%;height:250px;"></div>
Inside a string with Template Literals (don't use these with user supplied values!):
img(src=`/images/${sensor}.png`, style="width:20%")
Inside a string used to denote a function call. Note that you cannot use the ` symbol (back tick aka grave accent used in template literals) with function calls because you would have to ecompass the entire function call . This results in a string which is not going to be executed. You need to use string concatenation.
body(onload="initTemp('"+ sensor +"')")
Here is the official documentation for Pug interpolation:
https://pugjs.org/language/interpolation.html
Hope this helps. Corrections and suggestions always welcome!

To render variables directly in a string in a Pug template, you can use the typical ES6 interpolation. Example (assuming pageTitle is in scope, and passed as template context):
- var pageTitle = `Google | ${pageTitle}`;

Pug interpolates with a hash. #{interpolation}

Related

Significance of javascript function name in quotes in Angularjs

I'm going through a javascript file having some functions like this:
'form_validation': function(form,error_bin){
for(var field in form){
if(field.substr(0,1) != "$"){
this.validation_messages(field,form,error_bin);
}
}
}
I want to understand what is the difference between defining a function with quotes (like mentioned above) and without quotes
EDIT: I've also observed that the functions having name in quotes are being called from a different file (like: ServiceName.functionName()), while without quotes are being called from the same file.
This is an Angularjs code
The two are equivalent syntax for object literals. The quotes allow you to use keys that aren't legal variable names, like so:
var foo ={ 'variable name':2}
There's nothing significant about the fact that the value assigned to the object key is a function. In JavaScript objects are (almost) just key value pairs of strings and arbitrary objects.
JavaScript has something called Objects these are link associative array's in other languages. Object have item. Each item has a key(name) and a value. Key's follow regular JavaScript variable names. You can check valid variable names here. Valid variable names do not need to be in quotes. Sometimes, to include special characters, the name is a string.
my_value <- Valid
my-value <- Invalid (needs to be in string)
my value <- Invalid (needs to be in string)
both are same for javascript objects. but you should avoid using quotes as a coding standard.

Escaping string parameters in Django templates for a JavaScript function

I have a JavaScript function which returns a set of objects:
return Func("{{id}}", "{{name}}")
I have a problem with passing strings containing quotes, for instance "Dr.Seuss' "ABC""BOOk"" is invalid syntax.
I tried {{name|safe}} but to no avail. Any solution for this?
If I'm right in assuming that's a JavaScript function call you're trying to interpolate Django templating into, try the escapejs filter instead of safe.
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs

Angular : How does ng-click directory parses the expression without doubly curly brace?

I have a view as follwing,
<li ng-repeat="img in people.images">
<img ng-src="{{img}}" ng-click="setImage(img)">
</li>
Its working. But my doubt here is, the attribute ng-click should have been set the img inside doubly braces to be executed as in ng-src as ng-click="setImage({{img}})". Its shown below,
<li ng-repeat="img in people.images">
<img ng-src="{{img}}" ng-click="setImage({{img}})">
</li>
But the later is not working.
How the expression is parsed here and how does ng-click vary from ng-src?
I really confused here. Any help highly appreciated.
The difference is the following: Some of the directives use expressions, some don't. This is how they "vary" from each other. You may use the angular documentation to see, which directive use expressions and which don't.
Example for ng-click: https://docs.angularjs.org/api/ng/directive/ngClick It uses an expression:
Example for ng-src: https://docs.angularjs.org/api/ng/directive/ngSrc It doesn't use an expression:
ngClick lets you define a JavaScript-like expression, while ngSource lets you define an usual String, where you also may define an expression, inside the double braces. According to the AngularJS documentation, everything inside of the double braces is also an expression: https://docs.angularjs.org/guide/expression.
I think that the "need" to have the difference between "Expression" for "ngClick" and "String" for "ngSrc" come from the original attributes they derive from: onclick and src.
The attribute src is used to reference a resource as String, while using the attribute onclick, you may use javascript. The usual case is to call a function in onclick, i.e. onclick="doSomething();". I assume that angularjs uses these attributes as a base, this is why the workflow is similar. ngClick lets you use usual javascript expressions, while ngSrc lets you use a String and add a {{}} expression if you need to.
The benefit of using ngSrc with a variable, for example ngSrc="http://localhost/{{myRessource}}" is, that it is evaluated only after $scope.myRessource is set, not before. It uses the observer pattern to render the view as soon as the variable is set, as far as I know.
According to your example, the second one which doesn't work:
<li ng-repeat="img in people.images">
<img ng-src="{{img}}" ng-click="setImage({{img}})">
</li>
It doesn't work because of a syntax error. ngClick uses javascript expression, and the syntax of setImage({{img}}) is not correct - you would not use double brackets around variables either in a javascript function.
Further: $interpolate and $parse
Like stated above, some directives, like ngClick use expressions, while other directives like ngSrc use plain Strings combined with {{}}. The difference between the two on angularJs side is the following:
a directive using an expression is evaluated by angularjs using $parse (Read here from heading "Text and attribute bindings")
a directive using a String is evaluated by angularjs using $interpolate (Read here from heading "Context")
Example:
$scope.varOne = "asdasdasd";
var test1 = $interpolate("http://localhost/{{varOne}}");
$scope.displayOne = test1($scope);
At first, we declare a variable varOne. $interpolate returns a function which needs to be called with the scope, we will bind this to the local variable test1. Then we will call test1 using the $scope. As a result, we will have on displayOne the String http://localhost/asdasdasd.
var test2 = $parse("1+5-3");
$scope.displayTwo = test2($scope);
$parse is evaluating javascript expressions, as a test we may use the calculation "1+5-3". After calling test2, the result will be 3.
I prepared a fiddle, so you can see this: http://jsfiddle.net/wSN54/6/
You may also try using brackets in the $parse evaluation (the same that happens in your second example):
$scope.varTwo = 2;
$scope.varThree = 3;
var test2 = $parse("{{varTwo + varThree}}");
$scope.displayTwo = test2($scope);
This must resolve in an error, because the double braces are not used in usual javascript expression:
Check it out fiddle: http://jsfiddle.net/wSN54/8/
As far as I know, if you put img param inside double brackets, when the page is rendered, you will notice that the parameter inside setImage function is a value of img. If you put img without brackets you will have rendered "setImage(img)" and in both case that will work.
Example:
imagine that you have one item in people.images model, and its for example "example.jpg". If you use brackets in setImage function, when the page is rendered you will see the attribute "ng-click=setImage('example.jpg')", in another approach you will have "ng-click=setImage(img)". In first case AngularJS don't need to parse value from your parameter, because you already put 'example.jpg' like a parameter, in another case AngularJS will parse value from img parameter/item before your function is executed.
TLDR; ng-src $interpolate the argument as template where ng-click $parse the expression
Long version
Copied from angular official docs
param=ngSrc, type=template
param=ngRepeat, type=repeat_expression
details refer to https://docs.angularjs.org/api/ng/directive/ngSrc and https://docs.angularjs.org/api/ng/directive/ngRepeat
What is expression - https://docs.angularjs.org/guide/expression
What is template(markup) - https://docs.angularjs.org/api/ng/service/$interpolate

JsViews: Converter before helper function in data-link

Using JsViews is it possible to have a converter precede a helper function in a data-link property? Somehow like this..
<div data-link="{myConverter:~myFunction('param1'):}"></div>
Thanks!
If you mean that you want the converter to convert the value of the param1 field of your data object, and then pass it to the myConverter function, then no. The converter will process the result of the expression ~myFunction(...).
But you can create an equivalent helper function to your converter, and then chain the helpers:
<div data-link="~myFunction(~myConvert(param1))></div>"
BTW this will be data linked so that it updates when the param1 field changes. - I'm not sure if you meant to put quotes around 'param1'. If 'param1' is a string literal you are passing in, then data-linking to it won't have any reason to update, so you could just write:
<div>{{:~myFunction(~myConvert('param1'))}}</div>

variable in javascript statement

How does one add a variable string in this javascript statement?
where name may correspond to any valid string , say WebkitTransform or Moztransform,etc
document.getElementById('test').style.VARIABLE_NAME = 'rotate(15deg)';
My code doesn't seem to work when i set the VARIABLE_NAME to WebkitTransform, but it works fine if I use WebkitTransform directly, as in without naming it via a variable.
Thanks in advance :)
There are two ways to access members of a Javascript object.
Dot notation, which uses an identifier to access the member:
obj.member;
Bracket notation, which uses a string to access the member:
obj['member']
The latter uses a string to locate the member and you can just as easily use any expression. The value of the expression will be converted to a string so these are equivalent:
obj[{}]
obj['[object Object]']
If your expression is already a string it will be used as is, and in your case your variable holds a string so you can just do:
document.getElementById('test').style[VARIABLE_NAME] = 'rotate(15deg)';
There are 2 ways of accessing values in javascript objects. The first one is by using the dot operator(e.g. object.memberName). The second one is by using the square bracket notation(e.g. object['memberName']).

Categories