简体   繁体   中英

load static file in a template that extends other template - Django javascript

I want to load a javascript file in the template that extends my base_generic template. I am using generic listView to render the template.

Since I can not use "{% url %}" tamplate tag inside of "{% block %}" tag I hardcoded the link as follows:

<script src="static/js/search.js">

Unfortunately the file does not work and I get aa message that: "SyntaxError: expected expression, got '<' "

I guess it is because my view tries to render the template as html (am I right?) - my assumption is based on this post: SyntaxError: expected expression, got '<'

So my question is: how can I load a static file in the template that extends another template.

EDIT:

Here is my template:

{% extends "base_generic.html" %}


  {% block content %}


  {% if search_flag %}
  SEARCHFLAG ON
  {% else %}

  <h2 class="myh"> Książki: </h2>

  {% if book_list %}
  <script>
  var lista=[];
  {% for book in book_list %}
  var title="{{book.title}}";
  var authors=[];
  {% for author in book.author.all %};

    var aut="{{author.last_name}}";


    authors.push(aut);

  {% endfor %}

  var authorsStr=authors.join('; ');

  var book=[title, authorsStr]
  lista.push(book);

  {% endfor %}
  console.log("created list of books and authors - name: lista")
  </script>

  {% else %}

  <p>W katalogu nie ma książek</p>
  {% endif %}
  {% endif %}


  <script src="static/js/search.js">
  </script>


  {% endblock %}

You can use {% url "" %} in a block . To use static make sure to include {% load static %} directly after the extends template tag when you need it. Then you can:

<script src="{% static 'js/search.js' %}">

You don't use {% url %} tag to get path to you static file, just write this on the top of your template file:

{% load staticfiles %}

After that, you can get access to your static files by folowing constructions:

<script src="{% static 'js/search.js' %}">

Read more in documentation .

If you want to extend the base template, you have to add block script and extend it to your templates

base.html:

{% block scripts %}
{% endblock %}

index.html:

{% block script %}
    <script src="{% static 'js/search.js' %}">
{% endblock %}

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM