Using Django's template filters within a JavaScript script to manipulate an object's attribute

I am facing an issue where django's template filters are not working inside a js script when applied to an object's attribute.

When I use the following code, it results in a js SyntaxError:

<script>
    {{ obj.geometry.geojson | safe }}
</script>

However, if the filter is applied directly on the object itself, no error occurs:

<script>
    {{ obj | safe }}
</script>

The content of the GeoJson file mentioned above is as follows:

{ "type": "Polygon", "coordinates": [ [ [ 3, 36 ], ... }

I need to ensure that the quote character (") is not escaped into (&quot;) so that I can later use JSON.parse() to convert it from a string to an object.

Answer №1

To create a new GeoJson string and insert it into a template, follow the example below:

return render(
           request,
           'my_template.html',
           {'obj': obj, 'geo_json': json.dumps(obj.geometry.geojson)}
       )

Whenever you need to use GeoJson content, simply include it as shown below:

<script>
    {{ geo_json | safe }}
</script>

UPDATE:

You can also achieve this using context-processors or template-tags, but these methods may be complex and unnecessary...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for Implementing a Delay on Bootstrap Dropdown Hover

Is there a way to create a delay for the bootstrap dropdown feature while ensuring that it still appears on hover? If you want to test this, click here: http://www.bootply.com/YcVBzvXqrR This is the HTML code I'm using: <div class="container"&g ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

Decompress a substantial amount of JSON information using JSON.net

I have been gradually familiarizing myself with JSON responses and how to effectively manipulate them using JSON.net The specific data I am working with can be accessed at the following link: For instance, my current task involves extracting the "Copyrig ...

Is JsonEditor capable of editing JSON Schemas effectively?

For a while now, I have been impressed by the functionality of JSON-editor and have been using it to edit documents based on a specific JSON schema. But why stop there? Many users utilize JSON-Editor to make changes to JSON documents according to the corr ...

Creating a stripe_id for a subscription: A step-by-step guide

I recently integrated the Stripe API with django-allauth on my website. My goal is to assign a unique stripe_id to new users who have just subscribed. Everything was working fine until today when I encountered a new error that I haven't seen before: ...

How can you replace a public method in a specific class in Javascript?

I have a JavaScript class that I need to test: TestClass = function { // some code that utilizes initializeRequest this.initializeRequest = function() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); ...

I want to utilize a select drop-down menu for navigating between pages in my pagination, breaking away from the traditional method of using <a> tags

I have a select dropdown that is dynamically generated for navigation to other pages within the script. It lists the number of pages available for navigation. However, after selecting a page and loading it, the dropdown does not stay selected. I've tr ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

How can I use JavaScript to modify the style of the first unordered list (ul) element without affecting the

function displayMenu(){ var parentElement = document.getElementById("menuItem1"); var lis = parentElement.getElementsByTagName("ul"); for (var i = 0; i < lis.length; i++) { lis[i].setAttribute("style","display: block"); } } When the button is clicke ...

Using State.go in JavaScript involves waiting for it to finish before proceeding

After implementing a JS code snippet as shown below: exports.openTab = function(location) { var $state = app.getInjector().get( '$state' ); var opts = {}; var toParams = {}; toParams.id = "myPage"; $state.g ...

Utilizing AJAX to dynamically update a div's content by extracting a specific div from the retrieved data

Although I believe my code is correct, I am not very familiar with AJAX and have been struggling for hours to get it right. I've tried various approaches, including using filters, but nothing seems to work. The issue I'm facing is that the chat m ...

I'm feeling completely lost trying to understand cors in conjunction with fetch, particularly when an options request is

I am using whatwg fetch in the code snippet below: const headers = new Headers(); //uncommenting this causes the preflight options request to be sent //headers.append('x-something', 'foo'); const response = await fetch(&apos ...

`Save user edits on the webpage using Electron`

I am encountering an issue with my electron app. I use the window.loadUrl() method to navigate between pages. Some of these pages require users to input data that needs to be saved. The problem arises when a user enters information, moves to another page ...

Conceal a column within a nested HTML table

I am facing a challenge with a nested table column structure: My goal is to hide specific columns based on their index within the table. Can someone explain the concept behind achieving this? I am unsure of how to get started on this task. <table clas ...

Vue: Conditionally display a division depending on v-if, excluding cases where the div returns null

Within my HTML, I have implemented conditional rendering using v-if <div v-if="showdiv"> <p>Content 1 appears here</p> </div> <div v-if="!showdiv"> <p>Content 2 appears here</p> < ...

Setting up Pyldap with Django Auth LDAP in a Python 3 virtual environment

Having some trouble installing pyldap to integrate with django-auth-ldap. When attempting the following command: pip install pyldap An error occurs: In file included from Modules/LDAPObject.c:4:0: Modules/common.h:10:20: fatal error: Python.h: No suc ...

Pop-up box with hyperlink

I successfully integrated multiple modals into my webpage, using a template from w3school that I customized. Now, I am curious to see if it is possible for each modal to have its unique link. For example, when I open Modal 4, the URL would change to myweb ...

What is the best way to compare two arrays that have elements of different data types?

Can someone help me compare two arrays in TypeScript to see if they are identical? I'm having trouble with the current code. Here's what I have: let props:(string|boolean)[]=['abc','def',true,false,'xyz'] let propsCo ...

What is the most efficient way to include tags using a comma as a separator using the jQuery procedure

When using JSON to return an array of tags with the structure : 'FOOTBALL','BASKET','TENNIS' The goal is to create a tag list with quotes around each tag and a comma as a separator. To achieve this, the following function ca ...

What is the best way to determine the position of a letter within a string? (Using Python, JavaScript, Ruby, PHP, etc...)

Although I am familiar with: alphabet = 'abcdefghijklmnopqrstuvwxyz' print alphabet[0] # outputs a print alphabet[25] #outputs z I am curious about the reverse, for instance: alphabet = 'abcdefghijklmnopqrstuvwxyz' 's' = al ...