0

I am making an ajax call via jQuery and I am trying to style and inject the data back to the DOM.

If I have a django condition in my javascript variable, how can I revert it back into the DOM where django can still process it.

Example of Javascript

var injecthtml = 
'<a href="{% if user.is_authenticated %}'+datainfo.id+'{% else %}/register/{% endif %}"';
$("#somediv").html(injecthtml);

After doing this and when I go back to check the DOM the {% if user.is_authenticated %} is visible when I inspect my "a" tag.

Any idea on how this can be done?

1
  • Could you add more clarity on to what you're trying to accomplish? Commented Apr 24, 2015 at 14:52

2 Answers 2

1

I think you have some issues with ' and " not properly closed, try this instead:

var injecthtml = '<a href="/register/"></a>';
{% if user.is_authenticated %}

injecthtml = '<a href="'+datainfo.id+'"></a>';

{% endif %}

$("#somediv").html(injecthtml);
Sign up to request clarification or add additional context in comments.

Comments

0

If you're grabbing HTML from the server via AJAX, just modify the html on the server side and pass the correct information back.

For instance, user.is_authenticated will be true or false on the client side, so if you grab that and pass in the boolean value to your ajax call, the server can return the correct HTML for you to use, you don't need to pass in template style html.

Otherwise just request DATA from your server and then modify the html with the data you get back.

Django Templates replace all of that on the server side before the client ever gets it anyway, so you just want to replicate that if you're getting a specific piece of html.

Your question is a little confusing, but I think that's what you're looking for?

That piece of javascript won't work... django templates are rendered on the server side, so "{% %}" doesn't mean jack squat in html/javascript unless you have a client side templating engine (which is separate from django).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.