Garfonzo
Garfonzo

Reputation: 3966

Django - Escaping quotes in a template

I am trying to create a table that has rows of data that represent Contacts - a mix of people and company contacts. I want each row to be "clickable" so that, when clicked, that contact's form is pulled up for editing. To do that, I have something like this:

<tr onclick="window.location.href='{% url my.django.view %}'">...

You'll notice that the above has two levels of quotes: a double " after the equals, then a single ' to encapsulate the django template tag. There are two types of contacts: companies and people. I have my urls.py set up to handle this, with the following:

(r'^contact-details/(?P<cType>C)/(?P<cid>N)/$', contact_details),
(r'^contact-details/(?P<cType>P)/(?P<cid>N)/$', contact_details),
(r'^contact-details/(?P<cType>C)/(?P<cid>.*)/$', contact_details),
(r'^contact-details/(?P<cType>P)/(?P<cid>.*)/$', contact_details),

So, with the above, I have two urls for new contacts (distinguished by cType of C=Company or cType of P=Person) then two more urls for existing contacts (using cid for the primary key of the record).

The link imbedded in the rows of the table which list all the contacts looks like this:

<tr onclick="window.location.href='{% url cpm.contacts.views.contact_details 'P' c.pk %}'">

The problem I am having is that I can't pass in a 'P' or a 'C' into the link, because it would cause a third level of quotes and, thus, break the quotes all together. I just don't know how to escape that third level of quotes, around the P or C.

Any ideas?

Upvotes: 3

Views: 7320

Answers (2)

tom
tom

Reputation: 19153

You can just use double quotes around the "P", because the Django {% escape prevents the embedded double quote from closing the quotes for the HTML attribute.

<tr onclick="window.location.href='{% url cpm.contacts.views.contact_details "P" c.pk %}'">

Upvotes: 10

Amyth
Amyth

Reputation: 32949

maybe just create a simple jQuery / JS method to change window location and put it ina seperate JS file ?

function change_location(location){
    window.location = location;
}

and use it like:

<tr onclick="change_location({% url cpm.contacts.views.contact_details 'P' c.pk %});">

Upvotes: -2

Related Questions