Обновите значение элемента DOM базового шаблона для всех унаследованных страниц в FLASK - PullRequest
0 голосов
/ 29 марта 2020

Я новичок в python и flask. У меня есть база. html, ребенок. html и ребенок2. html. Я обновляю с дочернего. html элемента base. html DOM, но когда я нажимаю на child2. html базового. html элемент DOM остается по умолчанию. Я хочу обновить базу. html значение для всех унаследованных шаблонов. Заранее спасибо.

база. html

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
        <meta charset="UTF-8">
        <title>{% block title %} {% endblock %} - My App</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
              integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
              crossorigin="anonymous">

    {% endblock %}

</head>
<body>
<h1 id="set_hex">HEX: {{g.hex_val}}</h1>
<h5 id="base_pt" style="display: none;"></h5>
{% block content %}

{% endblock %}

    {% block scripts %}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="{{ url_for('static', filename = 'js/sweetalert2.all.min.js') }}"></script>




{% endblock %}


</body>
</html>

Я хочу обновить для все страницы set_hex для всех унаследованных страниц. Я также использую данную переменную, но она не показывает значение.

child. html

{% extends "base.html" %}
{% block title %}Child{% endblock %}
{% block head %}

    {{ super() }}

{% endblock %}

{% block content %}
    <h2>Child Content</h2>

    <div class="container">
        <br><br><br><br>
        <form class="form-inline">

            <div class="form-group">
                <label class="sr-only" for="myInput">Name</label>
                <input type="text" class="form-control" id="myInput" placeholder="Enter Hex rgb"
                       minlength="6" maxlength="6" pattern="[0-9A-Fa-f]{6}"
                       title="Enter six-digit hex" required style="text-transform:uppercase ">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
        <br>

        <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
        <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
    </div>


{% endblock %}


{% block scripts %}

    {{ super() }}

    <script>
        $(document).ready(function () {

            $('form').on('submit', function (event) {


                $.ajax({
                    data: {
                        name: $('#myInput').val(),
                    },
                    type: 'POST',
                    url: '/process1'
                })
                    .done(function (data) {

                        if (data.error) {


                            Swal.fire({

                                icon: 'error',
                                title: data.error,
                                showConfirmButton: false,
                                timerProgressBar: true,
                                timer: 1500
                            })

                        } else {

                            //$("#set_hex").text("HEX : " + data.name);


                            Swal.fire({

                                icon: 'success',
                                title: 'HEX Updated',
                                showConfirmButton: false,
                                timerProgressBar: true,
                                timer: 1500
                            })
                        }

                    });

                event.preventDefault();

            });

        });

    </script>
{% endblock %}

child2. html

{% extends "base.html" %}
{% block title %}Child{% endblock %}
{% block head %}


    {{ super() }}

{% endblock %}


{% block content %}

    <h2> Child 2 template</h2>



{% endblock %}

{% block scripts %}

    {{ super() }}

    <script>
        $(document).ready(function () {


        });

    </script>
{% endblock %}

app.py

from flask import Flask, render_template, request, jsonify,g
import json
import os
import pandas as pd

app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template('child.html')


@app.route('/child2')
def hello_world1():
    return render_template('child2.html')


@app.route('/process1', methods=['POST'])
def process1():

    hex_val = request.form['name']

    if hex_val:
        root_dir = os.path.realpath(os.path.dirname(__file__))
        dir_url = os.path.join(root_dir, "static/json_dir/", "data_file.json")
        data_json = json.load(open(dir_url))
        df = pd.json_normalize(data_json)
        df_HEX = df["Hex"]


        try:
            selected_HEX_index = df_HEX[df_HEX == hex_val].index[0]
            g.hex_val = hex_val
            return jsonify({'name': hex_val})
        except:
            selected_HEX_index = -1

        if selected_HEX_index == -1:
            return jsonify({'error': 'HEX not found!'})

    return jsonify({'error': 'Missing data!'})




if __name__ == '__main__':
    app.run()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...