如何在Javascript文件(.js)中使用Python Flask? [英] How to use Python Flask in Javascript file(.js)?

查看:81
本文介绍了如何在Javascript文件(.js)中使用Python Flask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当Javascript代码位于HTML文件中时,这不是问题. 但是,一旦我将script标记的内容移到js文件以在其他HTML文件中使用,就会出现无法读取图像的问题.代码如下.

script.js

function mouseOverSelf() {
    let img = document.getElementById("changeImg1");
    let m = document.getElementById("changeColor1");
    img.src = "{{ url_for('static', filename='img/edit_w.svg') }}";
    m.style.color = "white";
}

function mouseOutSelf() {
    let img = document.getElementById("changeImg1");
    let m = document.getElementById("changeColor1");
    img.src = "{{ url_for('static', filename='img/edit.svg') }}";
    m.style.color = "black";
}

function mouseOverExcel() {
    let img = document.getElementById("changeImg2");
    let m = document.getElementById("changeColor2");
    img.src = "{{ url_for('static', filename='img/spreadsheet_w.svg') }}";
    m.style.color = "white";
}

function mouseOutExcel() {
    let img = document.getElementById("changeImg2");
    let m = document.getElementById("changeColor2");
    img.src = "{{ url_for('static', filename='img/spreadsheet.svg') }}";
    m.style.color = "black";
}

index.html

<script type="text/javascript" src="{{ url_for('static', filename='js/script.js') }}"></script>

我该怎么办?

解决方案

解决方案是通过模板中的{% block %}标签而不是通过<script src=".."> html标签().

您有两个选择,javascript代码(与css相同)用于以下方面的加载和执行:

  • 特定页面(本地)
  • 所有页面(全局)

具有jinja2模板继承机制,如何执行以下操作:

base.html

<!doctype html>
<html class="no-js" lang="en_US">
<head>
  <meta charset="utf-8">
  <title>{% block title %}{% endblock %}</title>
  <meta name="description" content="{% block description %}{% endblock %}">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="manifest" href="{{ url_for('static', filename='site.webmanifest') }}">
  <link rel="apple-touch-icon" href="{{ url_for('static', filename='icon.png') }}">
  <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">

  {% block stylesheets %}

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" integrity="sha256-h20CPZ0QyXlBuAw7A+KluUYx/3pK+c7lYEpqLTlxjYQ=" crossorigin="anonymous" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  {% block stylesheets_others %}{% endblock %}
  <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-override.css') }}">
  <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-extend.css') }}">
  <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
  {% block stylesheets_local %}{% endblock %}

  {% endblock %}

  <meta name="theme-color" content="#fafafa">
</head>
<body>
  <!--[if IE]>
    <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p>
  <![endif]-->

  {% block body %}
    {% include 'includes/header.html' %}
    {% block content %}{% endblock %}
    {% include 'includes/footer.html' %}
  {% endblock %}

  {% block javascripts %}

  <script src="{{ url_for('static', filename='js/vendor/modernizr-3.8.0.min.js') }}"></script>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <script>window.jQuery || document.write('<script src="{{ url_for('static', filename='js/vendor/jquery-3.4.1.min.js') }}"><\/script>')</script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  {% block javascripts_others %}{% endblock %}
  <script src="{{ url_for('static', filename='js/vendor/vendor.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/plugins.js') }}"></script>
  <script src="{{ url_for('static', filename='js/main.js') }}"></script>
  {% block javascripts_local %}{% endblock %}
  <!-- Google Analytics: change UA-XXXXX-Y to be your site's ID. -->
  <script>
    window.ga = function () { ga.q.push(arguments) }; ga.q = []; ga.l = +new Date;
    ga('create', 'UA-XXXXX-Y', 'auto'); ga('set','transport','beacon'); ga('send', 'pageview')
  </script>
  <script src="https://www.google-analytics.com/analytics.js" async></script>

  {% endblock %}
</body>
</html>

my-page.html

{% extends 'base.html' %}

[..]
{% block stylesheets_local %}
  {{ super() }} {# to load the parent assets #}
  <style>
  /* You "Local" css goes here .. (if any) */
  </style>
{% endblock %}

{% block body %}
  [..]
{% endblock %}


[..]
{% block javascripts_local %}
  {{ super() }} {# to load the parent assets #}
  <script>
  // You "Local" javascript code goes here ..
  </script>
{% endblock %}

如果要通过以下方式加载其他JavaScript或CSS 外部库:对于特定页面,逻辑是相同的,则需要在您的页面中扩展{% block javascripts_others %}{% endblock %}{% block stylesheets_others %}{% endblock %}块模板,但不要忘记包含{{ super }}来加载父资产(如果有).

但是,如果您认为应该全局加载外部库,javascript或css,然后分别将它们添加到bootstrapfont awesome库下面的base.html中.因此,使用这种逻辑,您可以按正确的顺序加载任何页面的资产,而不会发生冲突.

但是碰巧您的代码(js或css)是为少数页面加载的,而不是不是所有页面(不是全局的)加载的,在这种情况下,请创建一个分隔的模板,然后将您的js或CSS代码放入正确的位置和顺序(就像我们之前所做的那样)

page-1.htmlpage-2.htmlpage-3.html ..

{% extends 'base.html' %}

[..]
{% block stylesheets_local %}

  {{ super() }} {# to load the parent assets #}
  {% include 'includes/mycss.css.html' %}

{% endblock %}

{% block body %}
  [..]
{% endblock %}


[..]
{% block javascripts_local %}

  {{ super() }} {# to load the parent assets #}
  {% include 'includes/myscript.js.html' %}

{% endblock %}

请注意,我如何命名部分模板只是约定,这是一个好习惯.

When Javascript code was in the HTML file, this was not problem. However, As soon as I moved the contents of the script tag to a js file for use in other HTML files, there was a problem with not being able to read the image. The code is as follows.

script.js

function mouseOverSelf() {
    let img = document.getElementById("changeImg1");
    let m = document.getElementById("changeColor1");
    img.src = "{{ url_for('static', filename='img/edit_w.svg') }}";
    m.style.color = "white";
}

function mouseOutSelf() {
    let img = document.getElementById("changeImg1");
    let m = document.getElementById("changeColor1");
    img.src = "{{ url_for('static', filename='img/edit.svg') }}";
    m.style.color = "black";
}

function mouseOverExcel() {
    let img = document.getElementById("changeImg2");
    let m = document.getElementById("changeColor2");
    img.src = "{{ url_for('static', filename='img/spreadsheet_w.svg') }}";
    m.style.color = "white";
}

function mouseOutExcel() {
    let img = document.getElementById("changeImg2");
    let m = document.getElementById("changeColor2");
    img.src = "{{ url_for('static', filename='img/spreadsheet.svg') }}";
    m.style.color = "black";
}

index.html

<script type="text/javascript" src="{{ url_for('static', filename='js/script.js') }}"></script>

How Can I do?

解决方案

the solution is to include the javascript code (the same with css) via {% block %} tag in the template, not via <script src=".."> html tag (<link rel="stylesheet" href="..">).

you have two option, the javascript code (the same with css) is meant to be loaded and executed for:

  • a particular page (local)
  • all pages (global)

with jinja2 template inheritance mechanism, below how you can do:

in base.html

<!doctype html>
<html class="no-js" lang="en_US">
<head>
  <meta charset="utf-8">
  <title>{% block title %}{% endblock %}</title>
  <meta name="description" content="{% block description %}{% endblock %}">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="manifest" href="{{ url_for('static', filename='site.webmanifest') }}">
  <link rel="apple-touch-icon" href="{{ url_for('static', filename='icon.png') }}">
  <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">

  {% block stylesheets %}

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" integrity="sha256-h20CPZ0QyXlBuAw7A+KluUYx/3pK+c7lYEpqLTlxjYQ=" crossorigin="anonymous" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  {% block stylesheets_others %}{% endblock %}
  <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-override.css') }}">
  <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-extend.css') }}">
  <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
  {% block stylesheets_local %}{% endblock %}

  {% endblock %}

  <meta name="theme-color" content="#fafafa">
</head>
<body>
  <!--[if IE]>
    <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p>
  <![endif]-->

  {% block body %}
    {% include 'includes/header.html' %}
    {% block content %}{% endblock %}
    {% include 'includes/footer.html' %}
  {% endblock %}

  {% block javascripts %}

  <script src="{{ url_for('static', filename='js/vendor/modernizr-3.8.0.min.js') }}"></script>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <script>window.jQuery || document.write('<script src="{{ url_for('static', filename='js/vendor/jquery-3.4.1.min.js') }}"><\/script>')</script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  {% block javascripts_others %}{% endblock %}
  <script src="{{ url_for('static', filename='js/vendor/vendor.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/plugins.js') }}"></script>
  <script src="{{ url_for('static', filename='js/main.js') }}"></script>
  {% block javascripts_local %}{% endblock %}
  <!-- Google Analytics: change UA-XXXXX-Y to be your site's ID. -->
  <script>
    window.ga = function () { ga.q.push(arguments) }; ga.q = []; ga.l = +new Date;
    ga('create', 'UA-XXXXX-Y', 'auto'); ga('set','transport','beacon'); ga('send', 'pageview')
  </script>
  <script src="https://www.google-analytics.com/analytics.js" async></script>

  {% endblock %}
</body>
</html>

in my-page.html

{% extends 'base.html' %}

[..]
{% block stylesheets_local %}
  {{ super() }} {# to load the parent assets #}
  <style>
  /* You "Local" css goes here .. (if any) */
  </style>
{% endblock %}

{% block body %}
  [..]
{% endblock %}


[..]
{% block javascripts_local %}
  {{ super() }} {# to load the parent assets #}
  <script>
  // You "Local" javascript code goes here ..
  </script>
{% endblock %}

if you want to load other javascript or css external libraries via e.g: cdn for particular page the logic is the same, you need to extend {% block javascripts_others %}{% endblock %} and {% block stylesheets_others %}{% endblock %} blocks in your template, but don't forget to include {{ super }} to load the parent assets if any.

But if you think an external libraries, javascript or css, should be loaded globally then add them in base.html respectively below bootstrap and font awesome libs. So with this logic you'll load the assets for any page with the right order with no conflict.

But it happens that your code (js or css) is meant to be loaded for few pages not all pages (not globally), in this case, create a separated template and put you js or css code and include it in the right place and order (like we did previously)

in page-1.html, page-2.html, page-3.html ..

{% extends 'base.html' %}

[..]
{% block stylesheets_local %}

  {{ super() }} {# to load the parent assets #}
  {% include 'includes/mycss.css.html' %}

{% endblock %}

{% block body %}
  [..]
{% endblock %}


[..]
{% block javascripts_local %}

  {{ super() }} {# to load the parent assets #}
  {% include 'includes/myscript.js.html' %}

{% endblock %}

note how i named partial template just convention, a good practice.

这篇关于如何在Javascript文件(.js)中使用Python Flask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆