Calling Django `reverse` in client-side Javascript

前端 未结 10 507
无人共我
无人共我 2020-12-13 02:22

I\'m using Django on Appengine. I\'m using the django reverse() function everywhere, keeping everything as DRY as possible.

However, I\'m having trouble

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 02:55

    I like Anatoly's idea, but I think using a specific integer is dangerous. I typically want to specify an say an object id, which are always required to be positive, so I just use negative integers as placeholders. This means adding -? to the the url definition, like so:

    url(r'^events/(?P-?\d+)/$', events.views.event_details),
    

    Then I can get the reverse url in a template by writing

    {% url 'events.views.event_details' event_id=-1 %}
    

    And use replace in javascript to replace the placeholder -1, so that in the template I would write something like

    
    

    This easily extends to multiple arguments too, and the mapping for a particular argument is visible directly in the template.

提交回复
热议问题