Django custom template tags in javascript

梦想与她 提交于 2019-12-23 05:21:07

问题


I have a custom template tag that returns suppose name of a student and roll number if passed as an argument id of the student.

@register.inclusion_tag('snippet/student_name.html')
def st_name_tag(profile, disp_roll=True, disp_name=True):
    #some calculations
    return {'full_name':student.name,
            'roll':student.roll_number,
           }

The template(included) consists of some Html file which is written in a single line(to avoid unterminated string literal error from js).

I simply want to call the st_name_tag from inside the JS function.

My JS looks like:

{% load profile_tag %}
<script type = "text/javascript">   
eventclick : function(st){
     var div = ('<div></div>');
     var st_id = st.id;
     if (st.status == 'pass'){
          div.append('<p>Student Name:{% st_name_tag '+st_id+' %}</p>');
     }
}

So far I tried the above method along with removing the + and '' signs from st_id varaible. That hasnt helped me at all. Help Please!


回答1:


You are trying to render a template based on the interaction by user. The first happens on the server (server-side as it is often referred to), and the latter happens on the user's browser.

The order that these happen is first to render the template on server, send and present in browser, then user interacts with js. Because of this fact, as I mentioned in the comment, it is not possible to affect the template rendered within javascript.

I would recommend you to use ajax in order to accomplish this. Whenever an iteraction occurs, you asynchronously make a request to the server to present you with new data.



来源:https://stackoverflow.com/questions/30909752/django-custom-template-tags-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!