pass django template file content to javascript - javascript

I want to pass a template file content to my javascript file for later use to create DOM elements there.
What I have tried is to pass it to js as a variable with an include tag like this:
<script>const list_item = {% include 'myapp/list_item.html' %}</script>
But this end up getting:
Uncaught SyntaxError: Unexpected token '<'
Is there a way I can pass template file content to js file?
Thanks in advance

Looking just at your sample (not making any recommendations about other possible ways to achieve the desired result), it should be:
<script>const list_item = "{% include 'myapp/list_item.html' %}";</script>
The content of the template file should be included as a string, otherwise it will keep throwing a syntax error.

Related

Django | JS variable inside dynamic URL

I'm trying to pass a javascript variable inside a dynamic url using Django. I have the following path
path('task-update/<str:pk>/', updateTask, name='task-update'),
I'm able to retrieve the "Task" fields I created (id, title, description, ...) depending on what task I select inside the HTML (this is done using AJAX and the Django-REST Framework). However, I'm having some trouble on rendering javascript values inside dynamic urls
var url = `{% url 'task-update' pk=${activeItem.id} %}`
The ${activeItem.id} is where I'm having some trouble, I tried assigning it to a variable and passing that into the URL but it doesn't work.
A workaround I've been using is
var url = `http://127.0.0.1:8000/task-update/${activeItem.id}/`
however I'd like to use django's template tags
After searching for quite a bit this was the best neat-looking solution I found (also the only one): django-js-urls.
Just pip install django-js-urls and add 'js_urls' to your INSTALLED APPS.
Afterwards add simply add JS_URLS to your settings.py file and put the names of the paths you'd like to use. In my case I only added task-update, it looks something like this
JS_URLS = (
'task-update',
)
Then, all you need to do is add the following in the URLs root module
from js_urls.views import JsUrlsView
urlpatterns = [
# other urls
url(r'^js-urls/$', JsUrlsView.as_view(), name='js_urls'),
]
And include the following js in the template
<script src="{% url 'js_urls' %}" type="text/javascript"></script>
URLs can be used using the window.reverse function
var url = window.reverse('task-update', { pk: activeItem.id });
I found a trick that might work under most circumstances:
var url = "{% url 'task-update' pk=12345 %}".replace(/12345/, ${activeItem.id});
It's clean, and it doesn't break DRY principle.

Django - Passing ID into url template tag using Javascript

How do I insert an id inside a url template tag using javascript? I tried this way and I did not get it. Can not find the route in the urls.py.
function Edit(pk){
window.location.assign("{% url 'authentication:edit_user' "+${pk}+" %}");
}
<!-- Other way -->
function Edit(pk){
window.location.assign("{% url 'authentication:edit_user' "+pk+" %}");
}
Error is:
Reverse for 'edit_user' with arguments '('+${pk}+',)' not found. 1
pattern(s) tried:
['authentication\/user\/edit\/(?P[0-9]+)\/$']
This can't possibly work. Template tags are evaluated server-side, well before the client-side Javascript can run.
You don't need to concatinate the string. The url tag takes parameter. So you can change your code to
window.location.assign("{% url 'authentication:edit_user' pk %}");
Reference - url tag

Node.js and express + hbs - unexpected identifier when passing variable to template

I have a node express app, and I am attempting to pass a variable through when rendering my index.hbs file, like so:
<!DOCTYPE html>
<html>
<body>
Hello.
Login with Facebook
{{req}} <!-- this works fine(ish) -->
<script>
var request = {{req}}; // This throws an error
console.log(request);
</script>
</body>
</html>
The {{req}} template variable gets outputted as [object Object] as expected, but when attempting to pass it through via javascript, I get Unexpected identifier thrown in console. I tried modifying to use triple curly braces instead of double curly braces but that didn't seem to make a difference.
What is the correct way to set template variables using javascript?
This is because your template engine is replacing {{req}} with only strings.
If you want to use {{req}} in your javascript tag. Using JSON.stringify(req) to pass in template engine as parameter and in your javascript tags using triple "triple-stash" {{{req}}} to parse the string into object
About triple-stash the doc can be found
http://handlebarsjs.com/ in HTML Escaping part
Hope it helps
Edited:
Find similar answer here
Passing an object to client in node/express + ejs?
I had this same problem with EJS. I was able to pass the object from my Express server to the template by stringifying the object:
//express server
res.render('index', {req: JSON.stringify(data)})
//template
var request = {req}

Adding jQuery script to a single view in Yii2

I am working on the basic template of Yii2. I have got a jQuery script views/usuario/js/create.js that it's only going to be used in one view views/usuario/create.php.
I'd prefer not to use ...
public $jsOptions = array(
'position' => \yii\web\View::POS_HEAD
);
... in assets/AppAsset.php in order to mantain loading of scripts at the end of the page.
create.js it's only needed in the create.php view so I'd prefer to load it just for the create.php view.
So I've tried unsuccessfuly to follow ippi's instructions
Firebug keeps throwing me this error:
SyntaxError: expected expression, got '<'
http://www.example.com/usuario/js/create.js
Line 1
I guess there could be a problem with the route param of ...
$this->registerJsFile('js/create.js');
... but I can't find it out.
Any help would be appreciated.
registerJsFile() needs an url, you should simply publish (make it web accessible) your file before registering it, e.g. :
$pub = Yii::$app->assetManager->publish(__DIR__ . '/create.js');
$this->registerJsFile($pub[1], ['depends' => ['yii\web\JqueryAsset']]);
Or you could create an asset bundle and registering it in your view.
Read more about publish() and registerJsFile().
Try to use $this->registerScriptFile('views/usuario/js/create.js');

Twig JS Inline template unable to parse

I'm new to Twig.js templating and having some trouble getting it to render some JSON correctly. I'm using jQuery to pull a JSON result from Youtube and passing it to an inline Twig template. Everything's working fine except within my template the actual text I need to extract from the JSON is under item.title.$t and the $ seems to be throwing it off. I get the error Unable to parse '$t' at template position0.
My full function is as follows:
$.getJSON('http://gdata.youtube.com/feeds/api/videos?q=stack+overflow&max-results=5&&v=2&alt=json', function(data){
var template = twig({
id: 'videos',
data: '{% for item in feed.entry %}<h1>{{ item.title.$t }}</h1>{% endfor %}'
});
var postsHTML = twig({ ref: "videos" }).render(data);
// Display the rendered template
document.getElementById("videos").innerHTML = postsHTML;
});
Is there a way to escape strange characters such as $ within a template? I can't find reference to such an ability in the documentation. I know the data is getting read in correctly as I can render the title object, just not it's $t propoerty. Thank you for your help!
After some more tweaking I tried accessing the property as an array again and it worked. See below:
'{% for item in feed.entry %}<article><header><h1>{{ item.title[\'$t\'] }}</h1></header></article>{% endfor %}'

Categories