How to store a template in an expression in Handlebars.js? - javascript

I want to place my templates on several places in the DOM without having to write the jQuery expression over and over again. I want to place my template in the DOM by just typing the variable/attribute {{template}} anywhere in the body.
Is this doable using Handlebars? If not, is there any other way for me to achieve this?

You need to use HandleBar helpers
handlebar_helpers
p.s. dont forget to use safestring else it will be escaped by default
Updating with answer based on ur comment
The link i provided did give out an excellent explanation. However please find below an example.
Assume your need to return a welcome message when a name is given
Handlebars.registerHelper('welcome', function(name) {
return new Handlebars.SafeString(
"<p>Hi "+name+", welcome to stackoverflow</p>"
);
});
Then calling
{{{welcome "sagittarius"}}} will return
Hi sagittarius, welcome to stackoverflow

Related

How to find a dynamic node class by pattern in JavaScript

I'm working on this WP plugin and I've been trying to get the ID of a custom post kinda thing that is declared in the body class on each page. So it goes like this;
<body class="(Bunch of other classes) ld-courses-1731-parent">
I'm trying to get the number 1731 in my JS function but the number is dynamic so I need to some regex matching with the string pattern.
Pattern: ld-courses-*INT VALUE*-parent
how can I do this with JS? Any help is much appreciated thank you so much.
You can use match if thats the only class in your body:
var classList = document.getElementsByTagName("body")[0].classList;
[...classList].forEach(function(thisClass) {
if (/ld-courses-\b/.test(thisClass)) {
var id = thisClass.match(/\d/g);
console.log(id.join(""));
}
});
<body class="another-class-before another-class-12-hasnum ld-courses-1731-parent another-class-12-hasnumaswell another-class-after">
</body>
Hi Laclogan in regards to your question yes it's possible for sure.
Correct me if i'm wrong but the number comes probably if it's changing for each post directly from the url.
The following site explains if this is the case how to get that number from the url.
https://www.sitepoint.com/get-url-parameters-with-javascript/
In addition you can use the function concat to combine the strings see this site for an example hope it helps.
https://www.w3schools.com/jsref/jsref_concat_string.asp
Could you confirm for me that the number is always present in the url or if this is not the case?

How to Get Html Element Attributes in AngularJS?

Edit: Everyone went on all kinds of tangents, but the question remains - how do I get an attribute of an html element inside an angular controller?
Here is a plnkr attempt: http://plnkr.co/edit/0VMeFAMEnc0XeQWJiLHm?p=preview
//$scope.myElem = angular.element('testDiv'); //this breaks angular
$scope.myElem = $document.find('testDiv'); //this doesn't break angular, but unclear what it returns
$scope.myAttr = $scope.myElem.name; //this returns nothing
If you need convincing that this is actually necessary - I need to find when a user scrolls through a div, as is shown here: http://jsfiddle.net/rs3prkfm/ Note that this has nothing to do with the question, simply a scenario. The question is simple - how do I get an attribute's value?
References:
Useless official docs: https://docs.angularjs.org/api/ng/function/angular.element
The only useful link that still doesn't work: http://mlen.io/angular-js/get-element-by-id.html
You could use the element api https://docs.angularjs.org/api/ng/function/angular.element
There should be only very few occasions where you would really need it, though.
You should manipulate the DOM using directives. The controller should only manipulate the data of the application and offer it to the html.
If you have direct manipulation on the Controller you can't, for example, bind several views to the controller. Also, if you change the id of one tag in the html and you are manipuling it directly in you controller, the controller will break.
Read this:
http://ng-learn.org/2014/01/Dom-Manipulations/
Hope it helps.
Use angular.element:
var myElem = angular.element("#testDiv"); // here you get your div
var myAttr = myElem.attr("name"); // you get: "testDiv"
Remember you have limitations using jqlite. If you want full functionallity of jquery element, import a full "jquery.js" before importing your angular script.
However, to manipulate the DOM you SHOULD use directives as stated by most of the answers.

What is dangerous in an HTML textarea?

I'm working on the profile section of my users.
They can define several things including their description ("About me") in a textarea, with a max of 400 characters.
In this description, I want to let my users use Font Awesome and Bootstrap icons. I also let them use JS tags (but not PHP ones). I guess this is pretty dangerous, therefore I wanted to know :
Is letting people use JS tags dangerous ? I know I must block functions like $.ajax but maybe there are somethings else.
Does a function which blocks string containing JS or PHP code exist in JS or jQuery ?
Is letting people use HTML tags and attributes dangerous for my site ?
Thank you !
As long as you escape all the tags before saving the form, I think it's all good.
You can do this with the following function:
function escapeTags(value){
return $('<div/>').text(value).html();
}
For eg. the following <script>alert("hello world")</script> will become <script>alert("hello world")</script>.
Also, you can do this with javascript only:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
Source: https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/
...if you take a look at comments you'll se that there's also a function that reverse my escapeTags function
// Encode/decode htmlentities
function krEncodeEntities(s){
return $j("<div/>").text(s).html();
}
function krDencodeEntities(s){
return $j("<div/>").html(s).text();
}
Yes, it's in fact very dangerous, and should only be allowed on a very limited set of "tags" or function calls.
Several systems like bbcode exist to address specifically these issues. i suggest implementing one of those.
They're easier to validate, and it is fairly easy to add new features to them.
It should be less work than validating actual js and php code and figuring out whether or not it is trying to do something malicious.

javascript regex in chrome extension

Okay, a little context. I want to modify some crappy HTML on a page that I use a lot. I'm doing this via my content_script "js", as defined in the manifest.json file of the chrome extension. The primary method I've been using is this sort of ugly thing:
var str1 = 'something already on the page';
var str2 = 'something already on the page, plus some extra stuff';
document.body.innerHTML = document.body.innerHTML.replace(str,st2);
I'm mostly trying to re-order form objects, and expand them a little to show more information, and filter/condense them to be less superfluous. I'd appreciate any pointer as to a better way to do this.
Anyway... here's my specific problem.
I want to retrieve pistol (or any string) from the following:
<form action="map.cgi?use-o" method="post" class="a"><input type="submit" value="pistol" class="m"\></form>
I tried every variation of the following:
str.exec(/value="([^]+)" class/);
and I'm either getting null or junk strings that I don't want. Ideas?
Thanks!
If you insist on regex, then use below one:
(?:value=")([^"]+)
Here is DEMO
Using JavaScript it will look like:
var value = document.querySelectorAll("input[type=submit]")[0].value;

Techniques to avoid building HTML strings in JavaScript?

It is very often I come across a situation in which I want to modify, or even insert whole blocks of HTML into a page using JavaScript. Usually it also involves changing several parts of the HTML dynamically depending on certain parameters.
However, it can make for messy/unreadable code, and it just doesn't seem right to have these little snippets of HTML in my JavaScript code, dammit.
So, what are some of your techniques to avoid mixing HTML and JavaScript?
The Dojo toolkit has a quite useful system to deal with HTML fragments/templates. Let's say the HTML snippet mycode/mysnippet.tpl.html is something like the following
<div>
<span dojoAttachPoint="foo"></span>
</div>
Notice the dojoAttachPoint attribute. You can then make a widget mycode/mysnippet.js using the HTML snippet as its template:
dojo.declare("mycode.mysnippet", [dijit._Widget, dijit._Templated], {
templateString: dojo.cache("mycode", "mysnippet.tpl.html"),
construct: function(bar){
this.bar = bar;
},
buildRendering: function() {
this.inherited(arguments);
this.foo.innerHTML = this.bar;
}
});
The HTML elements given attach point attributes will become class members in the widget code. You can then use the templated widget like so:
new mycode.mysnippet("A cup of tea would restore my normality.").placeAt(someOtherDomElement);
A nice feature is that if you use dojo.cache and Dojo's build system, it will insert the HTML template text into the javascript code, so that the client doesn't have to make a separate request.
This may of course be way too bloated for your use case, but I find it quite useful - and since you asked for techniques, there's mine. Sitepoint has a nice article on it too.
There are many possible techniques. Perhaps the most obvious is to have all elements on the page but have them hidden - then your JS can simply unhide them/show them as required. This may not be possible though for certain situations. What if you need to add a number (unspecified) of duplicate elements (or groups of elements)? Then perhaps have the elements in question hidden and using something like jQuery's clone function insert them as required into the DOM.
Alternatively if you really have to build HTML on the fly then definitely make your own class to handle it so you don't have snippets scattered through your code. You could employ jQuery literal creators to help do this.
I'm not sure if it qualifies as a "technique", but I generally tend to avoid constructing blocks of HTML in JavaScript by simply loading the relevant blocks from the back-end via AJAX and using JavaScript to swap them in and out/place them as required. (i.e.: None of the low-level text shuffling is done in JavaScript - just the DOM manipulation.)
Whilst you of course need to allow for this during the design of the back-end architecture, I can't help but think to leads to a much cleaner set up.
Sometimes I utilise a custom method to return a node structure based on provided JSON argument(s), and add that return value to the DOM as required. It ain't accessible once JS is unavailable like some backend solutions could be.
After reading some of the responses I managed to come up with my own solution using Python/Django and jQuery.
I have the HTML snippet as a Django template:
<div class="marker_info">
<p> _info_ </p>
more info...
</div>
In the view, I use the Django method render_to_string to load the templates as strings stored in a dictionary:
snippets = { 'marker_info': render_to_string('templates/marker_info_snippet.html')}
The good part about this is I can still use the template tags, for example, the url function. I use simplejson to dump it as JSON and pass it into the full template. I still wanted to dynamically replace strings in the JavaScript code, so I wrote a function to replace words surrounded by underscores with my own variables:
function render_snippet(snippet, dict) {
for (var key in dict)
{
var regex = new RegExp('_' + key + '_', 'gi');
snippet = snippet.replace(regex, dict[key]);
}
return snippet;
}

Categories