Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an object "company". When I use company inside of html, it works fine. But when I tried to use that object inside javascript I get the "Uncaught SyntaxError: Unexpected token &".

What I am trying to do is getting the objects from db then display them on html page then change up some divs using js.

the url:

('^all_companies$', 'companies.views.all_companies')

the view:

def all_companies(request): 
    companies = Company.objects.all().order_by('id')[:5];   
    return direct_to_template(request, 'all_companies.html', {'companies': companies} );

the html:

{% block sidebar %}
    <div id="sidebar">
        <!-- like google maps, short list of company info -->
        <ul>
            {% for comp in companies %}
                <li>{{ comp }}</li>                 
            {% endfor %}
        </ul>
    </div>
{% endblock %}

the js:

var tmp = {{ companies }}
share|improve this question
 
What does {{ companies }} evaluate to? Javascript doesn't seem to like that syntax. –  Greg Apr 27 '12 at 22:11
 
You should convert companies to JSON - only then JS would be able to read it –  hamczu Apr 27 '12 at 22:12
 
@Greg companies is the model object i get from db.. –  yao jiang Apr 27 '12 at 22:13
 
@hamczu can you explain a bit more for me please? thank you! –  yao jiang Apr 27 '12 at 22:14
 
looks like django syntax, you should probably specify that in your question and tags –  Guillaume86 Apr 27 '12 at 22:15
show 1 more comment

1 Answer

up vote 2 down vote accepted

You can add a template filter like that one: http://djangosnippets.org/snippets/201/

and use

{{ companies | jsonify }}

but I'm not sure it's a good idea to do that directly on a db object, it will be better to map them to a simple map of properties you need

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.