A place to put my things.

octubre 19, 2011

Pasing Django templates variables to Javascript code.

Archivado en: python — Etiquetas: , , , — Ruben @ 12:47

Here is the deal:

You need to convert a Python array or dictionary to a JavaScript array or Hash(dictionary) through a Django template.

The solution is to use autoscaping on Django templates.

This would be the Django view wich passes the array or dictionary variable:

def javascript(request):
    product1 = ['pendientes',  'pendiente pequeno',  '10 euros' ]
    product2 = { 'name': 'pendientes' , 'description' : 'Pendientes aro bronce', 'price' : '14.6 euro' }
    return render_to_response('javascript.html', {'product1' : product1,'product2' : product2,})

This would be the Django template with the Javascript code:

{% extends "base.html" %}
{% block content %}
<script type="text/javascript">

{% autoescape off %}

var product1 =  {{ product1 }} ;
var product2 =  {{ product2 }} ;

{% endautoescape %}

document.write(  'product1 description: ', product1[1], '<br/>' );
document.write(  'product2 price: ' , product2["price"], '<br/>' );

</script>
{% endblock %}


Advertisement

Dejar un comentario »

Aún no hay comentarios.

RSS feed para los comentarios de esta entrada. URI para TrackBack.

Deja un comentario

Fill in your details below or click an icon to log in:

Logo de WordPress.com

You are commenting using your WordPress.com account. Log Out / Cambiar )

Twitter picture

You are commenting using your Twitter account. Log Out / Cambiar )

Facebook photo

You are commenting using your Facebook account. Log Out / Cambiar )

Connecting to %s

Tema Shocking Blue Green. Blog de WordPress.com.

Seguir

Get every new post delivered to your Inbox.