How do I insert a JavaScript variable into a string containing Jinja markup?

238
November 08, 2019, at 06:20 AM

I have a javascript function that is trying to dynamically insert an anchor tag into a webpage, the href attr of which being a url for a flask route. This flask route accepts an argument username. I want to set username to the value of a javascript variable.

I have tried using template literals:

let username = 'user1';
let href = `{{ url_for("some.route", username=${username}) }}`
$("#elem").append('<a href=' + href + '></a>');

which throws a jinja2.exceptions.TemplateSyntaxError: unexpected char '$' error.

I've also tried string concatenation:

let username = 'user1';
let href = '{{ url_for("some.route", username=' + username + ')}}'
$("#elem").append('<a href=' + href + '></a>');

which results in the literal string + username + being passed to the route.

Any ideas on how to do this?

Rent Charter Buses Company
READ ALSO
IntersectionObserver.observe is not an object, how to use IntersectionObserver

IntersectionObserver.observe is not an object, how to use IntersectionObserver

I am creating a table with sticky columns using css position: stickyI want to style the columns differently when they are "stuck"

160
forEach is not finding the right user id when using sequelize findAll

forEach is not finding the right user id when using sequelize findAll

I have a scenario in which a user like his post, and it will fills a heart, coolIf user 2 likes the same post, user 1 heart becomes unfilled

165
Javascript: should sub/child objects use a dependency instantiated by their parent, or should they instantiate their own instance of the dependency?

Javascript: should sub/child objects use a dependency instantiated by their parent, or should they instantiate their own instance of the dependency?

My parent module async loads jquery3, in way that jquery3 is scoped to my parent moduleIn the parent I also load other submodules that use jquery

92