Hello,
I would like to get a url using a url pattern with JavaScript (inside a script tag within a django html template file).
Generally, this is how you can do it:
var url = "{% url 'pattern_name' argument %}"
And if your argument is a variable like this, I found at least one hack that works:
var arg = 'my_argument'
var url = "{% url 'pattern_name' temp %}".replace('temp', arg)
(If someone knows a better way to do that, I’m all ears.)
But, I have yet to find any way to construct the url using the url pattern when you have the url pattern as a variable like this (contrived to be simple):
var urlPatternName = 'pattern_name'
var arg = 'my_argument'
// var url = ??????
I’ve tried using JavaScript template strings like this:
var url = `{% url '${urlPatternName}' ${arg} %}`
Error: Could not parse the remainder: '${urlPatternName}' from '${urlPatternName}'
I’ve tried using the hacky .replace like this:
var url = "{% url 'hackPattern' hackArg %}".replace(hackPattern, urlPatternName).replace(hackArg, arg)
(Just to be sure I tried a single replace for a url pattern with a url that does not take arguments, that didn’t work either)
Error: Reverse for 'hackPattern' not found. 'hackPattern' is not a valid view function or pattern name.
I tried building the strings with +, too.
Error: Reverse for '" + urlPatternName + "' not found. '" + urlPatternName + "' is not a valid view function or pattern name.
And so it appears that the url tag is processed before any template strings or string replacement or string building happen.
Any suggestions?
Thanks