generate dynamic url (js to template)

:wave: community, hope you’re doing well and staying safe !!!
SCENARIO

:one: home.js fetches an Array and from that array we are showing list_item in list_view.
:two: final result below

<a href="{% url 'blog' 1 %}" class="list-group-item list-group-item-action"><div class="fw-bold">वसुलीसाठी चीप वापरल्याचा</div><div>Saturday, October 16, 2021, 11:29:14 PM</div></a>

ISSUE

  • how could we generate dynamic url for that list items ?

CODE THAT GENERATES HTML template

const build_list_item = function name(id, title, date) {
    this.id = id;
    this.title = title;
    const options = {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      second: "numeric",
    };
    this.date = new Date(date).toLocaleDateString(undefined, options);
    const anchor_el = document.createElement("a");
    const title_el = document.createElement("div");
    const date_el = document.createElement("div");
    anchor_el.href = `{% url 'blog' ${this.id} %}`;
    anchor_el.className = "list-group-item list-group-item-action";
    title_el.className = "fw-bold";
    title_el.innerHTML = `${this.title}`;
    date_el.innerHTML = `${this.date}`;
    anchor_el.append(title_el);
    anchor_el.append(date_el);
    return anchor_el;
  };

I think you got the idea what I’m trying to do, on the anchor url should work. but dynamic urls are not generating when we add href tag from JS, any other ways to accomplish this issue ?

Always remember that templates are rendered on the server while JavaScript runs in the browser.

The general process that I’ve mostly used for this is to create the url as a string with a “placeholder” that is replaced by the real value by the JavaScript.

1 Like