Recently I became interested of the jQuery template engine.
For the ajax call is very performant, because the data exchange is less.
But when I load my application the first time, I use only php and html for print the data, so for use this technic do I have to duplicate the template? One for php html and one for javascript?
How could I resolve this problem?
It is possible to use the same templates on the server side and the client. For example, mustache has implementations in several languages including PHP and Javascript. But generally I find it's easier to stick to one approach.
If you're using jQuery templating to render on the client anyway, why not render in Javascript the first time as well. To avoid needing an extra AJAX call, you can inject your data model into the page as a javascript object and pass that into the template renderer.
Here's an example. The json_encode function should be useful for this.
<script type="text/javascript">
// This line gets generated by your PHP code.
// You'll want to use the JSON methods instead of generating it by hand.
var myModel = { name: 'Fred', surname: 'Bloggs' };
$(document).ready(function() {
// Here you render the template using the data that's
// already in myModel
});
</script>
You could try Distal templating engine.
Your HTML page serves as part of the template.
<div>
Hi, <span data-qtext="user.name">Guest</span>
</div>
When you first load it displays "Hi, Guest" then you run the template and you can substitute for "Guest".
Related
I'm trying to figure out how to organize my javascript/django code.
So far I used to put my javascript page specific code in the same file. i.e I embed javascript in a <script> tag inside the template.
This creates a lot of mess when my JS code become large:
- django template variables {{var}} inside my JS code does not look well,
- I get an error when I try to minify it with tools like this one: http://jscompress.com/ ,
- And I just try to separate them as much as possible.
Today, in my embeded <script> tag my JS code looks like:
var app = {
func: function() {
// can I use the {% url %} tag here ?
$.post('/url/', {csrfmiddlewaretoken:'{{csrf_token}}', something:'value'} )
},
jsonFromServer: '{{pythonDict|safe}}', // I need this data structure,
};
As you can see, there are some values I need to pass form django to javascript, the most common is the csrftoken, for ajax requests. But sometimes I also pass a json dictionary that is needed for the app itself. Sometimes I want to pass the server time as well.
I'm thinking of moving the JS code to a separate file, I read that it is better way to organize like that. But I can't see how it is possible in a normal django app, without django have to render the .js files. And I believe it is better the JS file won't be served by django?
So how could I organize my JS without too much django code in it ?
I Don't know if it's "beautiful" but usually, I organize my code like that when it's about make web dev in MVC:
I put my <script> tag in the template of my page.
I write my js in an external file, traditionally in the /static/JS/my_template_name.js
As my gobal layout can have some JS code too, I make a great use of the JS modules: https://medium.freecodecamp.com/javascript-modules-a-beginner-s-guide-783f7d7a5fcc#.bjf4xwuq4
Usually, I don't have to do that.
When I need var from server in my js code, I make some Ajax calls.
But if you really want to process like that, I can suggest you to do something like this in your template:
<script>
var from_server = {{vars_from_server}};
</script>
Normally, if you pass a variable named vars_from_server to your template it will replace the placeholder between the script tags. Just think to format "vars_from_server" in a correct JS way.
After that, you will be able to access your vars in your scripts by accessing from_server variable from anywhere.
I'm writing a Django app and while somewhat familiar with Django I'm pretty unfamiliar with JavaScript. I'm adding a few lines of JavaScript into one of my pages in order to include a map.
The script simply encompasses initializing the map and then adding markers according to information saved in my database.
Given that there is so little code, would it still be considered bad practice to leave the script in the HTML template and pass information from my database using {{info}}?
If so, what method would you consider to be better?
I assume what you're suggesting is putting both the JS script and its required data into the template (the data being injected into the JS script through string interpolation)
You can see how this can get quickly out of hand. Below I provide levels of code organization, in approximate ascending order (the further you go to better, in general)
1. Include your JS using a script tag, not embedded into the HTML
First: putting the JS into its own .js file and including it via <script> tag is easy. So let's do that. Moreover, modern browsers can load files in parallel, so it's a plus to load the HTML and JS files simultaneously.
2. Avoid feeding the data into the JS using a Django template
Now the other problem I've seen people do is pass the data into the JS using a <script>data = {"info": "something"}</script> before including their JS code.
Which isn't ideal either for many reasons, stemming from the fact that the data is being string-interpolated in the Django template:
3. Make JS pull the data through a Django (REST) API
However since you said you are familiar with Django, I'd like to suggest you create a view that returns the data that your client side JS needs in JSON format. E.g. something that returns {"info": "something"} on /api/info.
There's lots of ways to achieve this, here's a start (albeit might be outdated)
Then I'd have the script.js file read the data with a simple HTTP GET call. Lots of JS libraries can do this for you easily.
Some advantages of this approach
Your code (the JS part) is independent from the data part (the JSON data)
You can easily view/test what's being fed into your JSON, since it's just a HTTP GET request away
Your HTML/JS part is completely static and hence cachable which improves the performance of loading the page.
The Python data conversion to JSON is pretty straightforward (no interpolation kung-fu)
Yep that's bad practice.
Consider defining static folder for your app as described on official django documentation page: Managing static files and upload your js via static template tag.
You could get data which in {{ info }} variable by creating separate django view which would return JsonResponse and then perform AJAX Request to fetch desired data from newly createdd js file.
In my Django projects, if I am using a "base" template that every other template extends, I just put a block called "extrahead" inside of the <head></head> in the HTML.
<html>
<head>
........ other header stuff
........ include other scripts
{% block extrahead %}
{% endblock %}
</head>
.............
</html>
... and then use that block just in the template you want the map on. That is assuming that it is just static js code?
I'm working on a project where it has a number of pages. Each page displays 10 rows where the layout that is using for each page is different. Until now I had the html code of each row in a javascript code and based on the page's url I was using the appropriate html code (if statement). The if statement is inside into a loop which is looping based on the number of rows. The results of the rows are coming from an ajax method. Now I want somehow to separate it so it can be more easily for me to maintain it, basically to remove the html code from the javascript and keep each row's html code into a different file.
Note: the Ajax is in a given time, is sending automatically requests to the php file for any new rows.
One solution which I came out is that I can use the php to create a variable with the html code .
Second solution is to create an array of each record with the html code and then pass it to jquery to print it.
Both solutions I don't know if are good solutions and can help me to maintain the project in the future.
You might consider a template library such as handlebars to help with templating. Frameworks such as AngularJS and Ember also excel at solving these kinds of problems.
Your Web Services API should be returning JSON though, not HTML fragments. Let the client build the DOM, and let the server focus on data.
You should return structured data (see JSON for example) to your AJAX request. This way, you can support multiple interfaces (e.g., a website, an application): each interface will get only the data, and will handle the rendering as it needs.
In your example, you ask for data via an AJAX request, your server responds with a JSON-structured response. JQuery reads it and converts it to javascript array thanks to jQuery.getJSON. With your array, you loop through each element and insert html elements into the webpage.
You have two options:
If your HTML templates is not changing frequently, the best way is to define html templates in your HTML structure using some java script template library (eg. Handlebars) and fill it with data from your AJAX (JSON) requests.
If your HTML templates change frequently or depends on some conditions (data) in row, you should create PHP partial views which generate proper html structure already filled with data.
For many rows it is better idea to create whole table server side to reduce requests.
I followed Hartl's Rails tutorial where he does Ajax using RJS and sending javascript in the response to be executed on the client side to edit the DOM.
But what do you do if you want just JSON sent in the response and not send javascript. This also means the javascript to manipulate the DOM should already be in the html file on the client. Is there a tutorial as good as Hartl's book on how to do this in Rails. Presumably it would use Jquery and some other stuff maybe that I've not heard of to make the code not be a million lines?
My best attempt at an answer is that it really depends on the scope and complexity of what you're trying to achieve. Generally, JSON shows up in views. If your application does not require you to dynamically retrieve JSON, that is, you can load it all when the view is initially rendered, then you can set an instance variable in your view's controller like so
#my_json = some_object.to_json()
Then, your instance variable is available in your view
<script type = 'text/javascript'>
var theJSON = <%= #my_json %>
</script>
Now, your data is available in the DOM, parsed nicely into JSON.
If your application requires you to dynamically retrieve JSON after the controller/view are loaded, then you should probably look into using AJAX to hit a particular controller's method that returns the JSON that you desire.
Here's a good RailsCast that can hopefully help you along your way Passing Data to Javascript
You should take a look at Ajax in Rails 3.1 - A Roadmap.
Basically, if you have a purely JS app (that get info from socket.io, or from a server with ajax request), and you need to show this data after processing it, what technique are you using?
Currently i'm creating the elements manually with code like
var myDiv = new Element('div',{ /* options */);
And injecting it where I need making all the DOM structure. I find this hard to maintain and especially for those designers that can code html, but they can't code html from JS.
Is there any way that will improve this process? Is it better to get the html from ajax? or just make html code in a string?
I'm looking for the most optimal in terms of maintenance and resources.
What you're looking for is a "template".
You have an HTML template (some divs, etc) and you bind this with the datas you provide in JS. Then, with whatever template engine you're using, you can get the full HTML.
Here are some template engines out there:
https://github.com/flatiron/plates
http://embeddedjs.com/
And a code sample using plates:
var Plates = require('plates'); // specific to node.js, see for client-side use
var html = '<div id="test">Old Value</div>';
var data = { "test": "New Value" };
var output = Plates.bind(html, data);
console.log( output ); // '<div id="test">New Value</div>'
You can store your templates either in a single file ("templates.html") loaded through ajax, or by storing it in the HTML page (not really recommended for maintenance matters).
If you store them all in an external file, you can do something like this:
templates.html:
<!-- text/html isn't parsed by the browser so we can put anything in it -->
<script type="text/html" id="template1">
<!-- put your template in there
</script>
And you can get its content through getElementById( 'template1' ).
Easiest way for you if project is in late stage to add something like jQuery.template plugin and create templates in separate files. Then, use backend to combine those peaces in single page and on DOM Ready fire up your client side app.
If your project is in early stage use AngularJs or BackboneJS frameworks. Believe me it is worth every cent :)
I would recommend you take a look at Backbone.js.
Backbone.js gives structure to web applications by providing models
with key-value binding and custom events, collections with a rich API
of enumerable functions, views with declarative event handling, and
connects it all to your existing API over a RESTful JSON interface
I use backbone even if I am not over a RESTful interface. It's pretty easy to separate the structure from the behavior ... You can achieve the same using jQuery but it wont be as neat and clean. It's one of the MV* framework. You have:
Models containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control.
Collections are ordered sets of models.
Views: The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page
Routers provides methods for routing client-side pages, and connecting them to actions and events
It's getting attention recently. Apps that were created using Backbone include:
FourSquare
LinkedIn for Mobile
This is a great resource if you're starting to work with Backbone.
Distal Templates http://code.google.com/p/distal/ :
<table id="a">
<tr><th>OPINIONS</th></tr>
<tr data-qrepeat="m keywords"><td data-qtext="m.name"></td></tr>
</table>
Then call:
distal(document.getElementById("a"), {
keywords: [
{name:"Brilliant"}, {name:"Masterpiece"}, {name:"Witty"}
]
});
will become:
<table>
<tr><th>OPINIONS</th></tr>
<tr><td>Brilliant</td></tr>
<tr><td>Masterpiece</td></tr>
<tr><td>Witty</td></tr>
</table>
And injecting it where I need making all the DOM structure. I find this hard to maintain and especially for those designers that can code html, but they can't code html from JS.
Another option is modest. As you can see from the documentation, it obviates the need for HTML chunks in javascript. The designers can change the HTML structure without needing to look at the javascript, and javascript coders can use parameters defined by the designers to fill in the data (all in javascript).
This example is from the readme:
HTML:
<div>
<contact>
<name>Casey Jones</name>
<phone>123-456-7890</phone>
</contact>
</div>
Javascript:
var contact = {
name : "Casey Jones",
cell : "123-456-7890"
};
var out = modest.render('contact',contact);