The function url_for is failing to interpret the variables I am passing to

My goal is to allow users to upload images that are then displayed to all users. The variable "Data" holds the file name (e.g., "files/dog.png"). However, when I try to set the newImg.src value as "{{url_for('static', filename = data )}}", it only turns into "/static/". Below is my code:

var chatDiv = document.getElementById('messages');
const newImg = document.createElement("img");
newImg.src = "{{url_for('static', filename = data )}}";
chatDiv.appendChild(newImg);

I attempted to use Jinja2 string interpolation like this:

newImg.src = "{{url_for('static', filename = data)}}";

But this resulted in an error:

jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

Even after removing the brackets, my code still doesn't work. Any help would be greatly appreciated!

Answer №1

Great news! I discovered a solution to the problem. Simply utilize the .replace method to substitute the string with a different variable.

newImage = "{{url_for('static', filename = 'content')}}".replace('content', content)

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

Shifting a div element around the webpage and letting it fall into place if it intersects with another div using plain JavaScript

Check out this jsFiddle link. Upon opening it, you will encounter a moveable div. However, I am looking to enhance this functionality by allowing the div to disappear if moved to the 'trash' area. Essentially, when you place the moveable div in t ...

Retrieving Ajax Data Using C#

I am struggling to send data through Ajax to a C# file. Whenever I check the received data, it always comes back as null. Could there be an issue in my code? Javascript file $(".save").click(function () { var ss = "Helloo!"; $.ajax({ typ ...

Retrieving server information using AJAX in React

I've been attempting to utilize an AJAX call in order to fetch server data for my React Components. However, I'm encountering difficulties when it comes to displaying it with React as I keep receiving this error: Uncaught TypeError: Cannot read ...

Unable to modify the styles of nested Material UI components

I am currently customizing the styles of the card and cardContent components in material ui. I have implemented them within functional components and am facing an issue with overriding the root style of each component. Specifically, I am struggling to modi ...

What is the importance of having the http module installed for our Node.js application to function properly?

After exploring numerous sources, I stumbled upon this code snippet in the first application: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); r ...

Sorting and filtering data using AngularJS filter and orderBy inside a controller or factory

I am currently working with a factory that looks like this: app.factory("ModuleFactory", function (api, $http, $q, filterFilter) { var moduleList = []; var categoryList = []; var moduleTypeList = []; var academyModuleTypeList = []; var mostUsed = []; var ...

Uninstalling NPM License Checker version

Utilizing the npm license checker tool found at https://www.npmjs.com/package/license-checker The configuration in license-format.json for the customPath is as follows: { "name": "", "version": false, "description&quo ...

What is the process for arranging multiple text boxes beside a radio button upon selection?

Displayed below is the HTML code for a page featuring three radio buttons- <html> <body> <form> <input type="radio" name="tt1" value="Insert" /> Insert<br /> <input type="radio" name="tt2" value="Update" /> Update<b ...

When an Ajax post request is made, the data being sent is appended to the JSON response

Having a dilemma with my ajax call: $.ajax({ url: '/assets/functions.php', type: 'POST', data: { "functionCall": "get-uploads", "type": type }, dataType: 'json', success: function (data ...

Adjust the aesthetic based on whether the field is populated or empty

I have a simple text field on my website that triggers a search when the user inputs a value. I am wondering if it is possible to style the text field differently depending on whether it is empty or has content. Specifically, I want to change the border c ...

incorporating event handlers to references retrieved from bespoke hooks

I have designed a simple custom hook in my React application to manage the onChange events of a specific input element. const useInput = () => { const ref = useRef(null); const handleChange = () => { console.log("Input has been ...

Rails backend is struggling to receive Crossrider ajax post requests with JSON payload

I am encountering an issue where my attempts to post a JSON object to a remote server (Rails) are failing. The POST parameters seem to be converted to a url-encoded string instead of being sent as 'application/json'. Here is an example of what I ...

Enhance DataTables functionality by including the ability to select which script to execute

Currently, I have a DataTables displayed with the provided code, utilizing server-side processing which is functioning properly. I am interested in implementing a dropdown menu above the table that allows users to select from options such as: Product Gr ...

Is it possible to utilize an API response within a conditional statement in NextJS?

I am working on a change password feature that interacts with an API for verification. If the current password entered is incorrect, I want to display an error message. If you have any suggestions on how to proceed or if there are any flaws in my approach ...

Opening the Gmail app from a link using JavaScript

What is the best way to open the Gmail app from a hyperlink? This link opens WhatsApp <a href="https://wa.me/">whatsapp</a> <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1f190f ...

When attempting to use focusin/focusout, I encountered the following error: Uncaught TypeError - The property 'addEventListener' cannot be read from null

When attempting to utilize the DOM events focusin/focusout, I encountered an error: Uncaught TypeError: Cannot read property 'addEventListener' of null. The issue seems to be originating from main.js at lines 18 and 40. I am using Chrome as my b ...

Sped up object outpacing the mouse pointer

I'm currently developing a drag and drop minigame, but I've encountered an issue with the touch functionality. The draggable function (using only cursor) works flawlessly, however, when I tried to implement touch support for mobile and tablet use ...

Setting up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Setting up React Router in a nested directory with a flexible route structure

As a newcomer to react router, I am seeking guidance on setting it up in a specific scenario. Imagine we have a PHP application running on 'http://www.example.com'. Within this setup, there is a react application located at 'http://www.examp ...

Mix up table data cells using Javascript/jQuery

Can anyone provide me with some helpful tips? I'm really struggling with this. My Objective I aim to create a table with two columns ("name" and "rating"), consisting of 5 rows. 2 of these rows should have a random "rating" between 6-10 2 other ro ...