jinja2 variables in javascript - javascript

If I have written jinja2 variables in javascript, for example
var array = [{{count}}...
and it works, will it work even if I move the code to a separate js file? Is there anything else I need to know about this practice?

You can certainly create a Jinja2 template that contains Javascript with Jinja2 variables, render that into a JavaScript file, and serve it to your users. Jinja2 doesn't care what kind of file you are rendering.
An important consideration is that you are changing a static file to a dynamic file. A typical Javascript file is static but you are now making it dynamic which puts additional load on your servers.
A typical solution is to use static JavaScript but render JavaScript data into your HTML page that the JavaScript file can access.

I came across this looking for the same kind of solution, and it was pointed out to me somewhere else that the data attribute in HTML is a good solution here as well.

Related

Python: Setting JavaScript Variables With Beautifulsoup?

Most of the pertinent questions I see answered online revolve around accessing JS variables from parsed pages. I want to go the other way as I have an HTML page which is being printed in python by beautifulsoup. Pretty easy stuff except that the page contains a bunch of dynamic JavaScript (GUI stuff) which I am not sure how to pre-populate on render without things getting messy.
To clarify: The page is being rendered by a python script running on a server. The python script retrieves a bunch of market data which it slices/dices and then is supposed to populate various JS variables in my HTML page. Again the static HTML is fairly straightforward and I've done that before. But populating the JS variables and arrays could get tricky. FYI - this is a single page and thus it's not worth setting up Flask or Django.
Finally, I wonder if it may just be easier to skip beautifulsoup and simply parse a static HTML file and pre-populate placeholder strings.
Thanks for any pointers, insights, or even better: examples ;-)
If I understood it correctly you could try to create an script tag at the end of the html file with the help of beautifulsoup. In this script tag you could just set the variables like this.
your_soup is the soup element of your page
from bs4 import BeautifulSoup
variable = "Example"
temp_soup = BeautifulSoup('<script>var yourvariable = ' + variable + '</script>')
script_tag = temp_soup.html.body.script
your_soup.body.insert(len(your_soup.body.contents), script_tag)
I hope it works.

How many ways are there to maintain handlebars template in client side

In my application we are templating handlebars from client side(we are not templating from server side).So till now we used maintaining all templated inside of the html file using script tag like in the following way.
<script id="selectdropdownTpl_mobile" type="text/x-handlebars-template">
<option value="{{optValue}}" label="{{name}}">{{name}}</option>
</script>
Whenever I want template, I am just compiling and appending compiled result to dom just like following way
var alertCompilation= Handlebars.compile(document.getElementById("selectdropdownTpl_mobile").innerHTML)
alertCompilation({"optValue":"test","name":"firstApp});
Working fine,but what we are thinking to separate all handlebar templates into another file.so it's easy to maintain html file.
Regarding this,I thinking to move all the templates into .js file inside of the file just creating global variable,it is object in the following way.
//fileName test.js
var templates={
"selectdropdownTpl_mobile":"template code"
}
whenever I want, I can access template code like in the following way.
var alertCompilation= Handlebars.compile(templates["selectdropdownTpl_mobile"]);
alertCompilation({"optValue":"test","name":"firstApp});
This way also working fine,What I want to know is this good way or not.If it is not good way How shell do this.
I heard about .hbs file, basically it contains pre-compiler template.It's usefull If I template from server side but in my case templating happening in client side itself.
can anyone suggest me,which way is better.

Django: render staticfiles through template engine at deploy-time

I want to render some static files (*.js in particularly) using Django template variables. I believe this is a common use-case, especially when doing anything AJAX-y; I don't want to hardcode AJAX urls in my .js files any more than I want to hardcode them in my .html files. Buuuut of course I don't want those static files to have to run through the template engine at every client request because this will be slow. I am referring to things like URLs (which do not change after compile/deploy) or static (non-db) model attributes. (I suppose there are use cases where these things might be changed at run-time - this is Python, after all- but I think they are uncommon). For some possible template variables (e.g. model fields), of course the file must be rendered at the time of the client request, but this is not what I'm talking about.
So wouldn't it make sense to render some of my static files through the template engine, for a subset of possible template variables, perhaps at the same time as collectstatic?
As far as I can tell this is not currently the case. To be clear, what I am looking for is a solution to render static files through the template engine at compile/deploy-time so that at "client-request-time" they are in fact plain old static files.
Such an approach would avoid these hacks:
DRY URLs in Django Javascript
Using the Django URL Tag in an AJAX Call
Disclaimers:
Yes I know there are template engines out there for javascript (mustache, handlebars, prototype, etc). Why should I add another template engine to the stack when Django already has one? Plus the syntax collides! That seems silly.
This looks like it takes a crack at it, but it's complicated and not fully implemented.
So:
Is there a solution out there that I am missing?
If not, is there a way to hook into collectstatic (like a pre-collectstatic hook) that would allow one to render certain static files through the template engine before "collecting" them?
EDIT:
No responses yet...is this a really dumb question, and I'm missing something obvious? If so...go ahead and let me know...
There are several frameworks for Django for same purpose: django-pipeline, django-assets, and etc. which integrates different static files processing strategies, with varying degrees of difficulty configuring.
I use an external tool - Grunt (it requires node.js) - for asset post-processing after collectstatic. It is easier and has a lots of plugins for any purpose (source validation, css/js/images minification, merging, testing and etc.).
It is possible to hook in collectstatic by a custom static files storage with overrided post_process method.
example/settings.py
STATIC_ROOT = 'assets'
STATICFILES_STORAGE = 'example.storage.MyStaticFilesStorage'
example/storage.py
import os
from django.contrib.staticfiles.storage import StaticFilesStorage
from django.core.files.base import ContentFile
from django.template import Template, Context
class MyStaticFilesStorage(StaticFilesStorage):
def post_process(self, paths, dry_run=False, **options):
# don't even dare to process the files if we're in dry run mode
if dry_run:
return
js_template_data = {'foo': 'bar'} # template variables
js_template_extension = '.jst'
js_extension = '.js'
for original_name, (storage, path) in paths.items():
processed = False
saved_name = original_name
original_path, original_extension = os.path.splitext(original_name)
if original_extension == js_template_extension:
with storage.open(path) as original_file:
saved_name = original_path + js_extension
if hasattr(original_file, 'seek'):
original_file.seek(0)
original_source = original_file.read()
c = Context(js_template_data)
saved_source = Template(original_source).render(c)
self.delete(saved_name)
self.delete(original_name)
self._save(saved_name, ContentFile(saved_source))
processed = True
yield original_name, saved_name, processed
A completely different way to approach the problem would be to ask if you really need to get those URLs in javascript--instead, can the Javascript get the URLs from things like data attributes in your HTML?
In other words, you might have wanted:
homepage.html:
<div id="pop-up-modal">pop me up</div>
homepage.js:
$("#pop-up-modal").click(function {
$.ajax("{% url 'some-class-name %}")
...
});
When it can often be more straightforward to do something like:
homagepage.html:
<div id="pop-up-modal" data-popurl="{% url 'some-class-name' %}">pop me up</div>
homepage.js:
$("#pop-up-modal").click(function {
$.ajax($(this).data('popurl'))
...
});
I think that django-medusa would suit your needs.
By setting up a renderer and using the disk based backend, generating the static files would be as easy as:
django-admin.py staticsitegen
You aren't crazy. I was frustrated by this as well and found myself hacking something together for each new Django project I tackled. I think the reason for the lack of direct solutions is that this is mega-drought bone DRY. Its super easy to just hard code these things and call it day. This and the two most common use cases for this involve generating code in one language from code in another which tends to be viewed as suspect.
I've recently published a new Django package django-render-static that solves this problem generically. It piggy-backs on Django's existing template engine infrastructure. A management command called render_static should be run before collectstatic. This command will look for templates registered in settings (or passed as arguments) and render them to your static file location on disk. They're then available for whatever normal static file packaging pipeline you have configured.
I'm sure there are more use cases, but the two most common I've found are providing a reverse utility in static JavaScript thats equivalent to Django's and auto-translating define-like python structures (i.e. choice fields) into JavaScript. The app provides template tags that do both.
The JavaScript url reversal code is guaranteed to be functionally equivalent to Django's reverse function. I won't bother plopping example code down here because it's been well documented.

How to transfer mvc view javascript code to separate js file

I am using Knockoutjs in my asp.net MVC-5 application. I have the following javascript in view:
<script type="text/javascript">
var model = "#Html.Raw(Json.Encode(Model))";
$.get("#Url.Action("_CityPartial")" ...)
//any much more code using similar Html helpers + pure javacsript code.
</script>
Now i want to know, is there any way to transfer this javascript code in a separate js file (keeping Html helpers as it is).
I want to transfer javascript code to separate file because i dont want any user to check my javascript code (using chrome inspect element or any other way).
If the transfer is not possible than please let me know if there is a any way to minifiy the javascript in view itself ??
You could create an external .js file with your code in and pass your serialized json object to it like this:
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
DoThis(model);
</script>
This has the benefits of keeping the main body of javascript in a separate file.
Any other razor variables can be passed across to the methods defined in the javascript in the same manor as the model has been above.
However as Stanyer mentions this is still javascript and it will run on the client.
You can load it via an external JavaScript file, but unfortunately as JavaScript is a client-side scripting language regardless of whether its loaded inline or externally, the client can still view the code which is being executed on their browser.
You mention minifying - again this can still be interpreted by a client if they really wanted to see your code, but there are many tools online which can minify your JavaScript for you.
Examples:
http://jscompress.com/
http://www.jsmini.com/
No you cant keep the #Html helpers in external javascript file. They are all server side syntax and will be rendered in your HTML page inline.
What maximum you can do is, assign it in a var variable in your page and refer it inside a external page.

Passing data from my razor view to my js file

I'm searching for the best way to pass data from my razor view to my js file. For example, lets say we have a jquery dialog configured in the js file. For buttons text on this dialog, I would like to localize it (through resource files FR/NL/UK). The translations are available with #UserResource.ButtonDelete + #UserResource.ButtonCancel
Below are the different solutions I see:
Using the nice RazorJS nuget package to allows razor code inside my javascript file. It works pretty well. But the question is: is it a bad practice to compile js files in order to use razor syntax inside the scripts?
Declaring global variables in the js script file and assign value from the view like this:
In the view:
<script>
var labelButtonDelete = #UserResource.ButtonDelete;
</script>
In the js file:
alert('The text for my button is ' + labelButtonDelete);
What is the best way to pass data from razor to js file? Do you have another alternative?
Thanks anyway.
I've been using something like your second approach for some time without any issues. The only difference is that I'm using a singleton in my JS file to avoid polluting the global javascript namespace.
But if you will be doing more serious client side stuff, your Javascript code will follow a more object oriented structure, and from there you almost automatically get a single initialization/constructor path where you can pass your localized values.
That RazorJS looks nice, but I'm not sure if I'm comfortable mixing Javascript with Razor. Might do it for a small project, but I can see it becoming really messy if you have lots of Javascript files.
After all, I still consider the resources/localization code to be related to the view. The Javascript should only implement functionality in my opinion.

Categories

Resources