如何在一条路由内调用多条路由?


问题内容

我有一个dashboard.html页面,其中包含三个标签。这些选项卡的外观相同,但是功能不同,因为它们是通过后端的不同方法呈现的。

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1">

<style>

* {box-sizing: border-box}

body {font-family: "Lato", sans-serif;}



/* Style the tab */

.tab {

  float: left;

  border: 1px solid #ccc;

  background-color: #f1f1f1;

  width: 30%;

  height: 300px;

}



/* Style the buttons inside the tab */

.tab button {

  display: block;

  background-color: inherit;

  color: black;

  padding: 22px 16px;

  width: 100%;

  border: none;

  outline: none;

  text-align: left;

  cursor: pointer;

  transition: 0.3s;

  font-size: 17px;

}



/* Change background color of buttons on hover */

.tab button:hover {

  background-color: #ddd;

}



/* Create an active/current "tab button" class */

.tab button.active {

  background-color: #ccc;

}



/* Style the tab content */

.tabcontent {

  float: left;

  padding: 0px 12px;

  border: 1px solid #ccc;

  width: 70%;

  border-left: none;

  height: 300px;

}

</style>

</head>

<body>

  <div class="tab">

    <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>

    <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>

    <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  </div>

  <div id="London" class="tabcontent">

    <h3>London</h3>

    <p>London is the capital city of England.</p>

  </div>



  <div id="Paris" class="tabcontent">

    <h3>Paris</h3>

    <p>Paris is the capital of France.</p>

  </div>



  <div id="Tokyo" class="tabcontent">

    <h3>Tokyo</h3>

    <p>Tokyo is the capital of Japan.</p>

  </div>



<script>

function openCity(evt, cityName) {

  var i, tabcontent, tablinks;

  tabcontent = document.getElementsByClassName("tabcontent");

  for (i = 0; i < tabcontent.length; i++) {

    tabcontent[i].style.display = "none";

  }

  tablinks = document.getElementsByClassName("tablinks");

  for (i = 0; i < tablinks.length; i++) {

    tablinks[i].className = tablinks[i].className.replace(" active", "");

  }

  document.getElementById(cityName).style.display = "block";

  evt.currentTarget.className += " active";

}



// Get the element with id="defaultOpen" and click on it

document.getElementById("defaultOpen").click();

</script>



</body>

</html>

该视图看起来与此视图相似。当我单击选项卡时,未出现所需的视图时出现问题。

# Dashboard
@app.route('/dashboard')
@is_logged_in
def dashboard():
    form1 = Add_Warehouse(request.form)
    return render_template('dashboard.html',form1=form1)

# Pending user registration
@app.route('/pending')
@is_logged_in
def pending_registration():
    cur = mysql.connection.cursor()
    result = cur.execute('SELECT * from registration')
    data = cur.fetchall()
    if result>0:
        return render_template('dashboard.html', users=data)
    else:
        msg = 'No Pending registration'
        return render_template('dashboard.html',msg=msg)
    cur.close()

# # Company accepting users
@app.route('/accept/<string:id_val>',methods=['POST','GET'])
@is_logged_in
def accept(id_val):
    cur = mysql.connection.cursor()
    cur.execute('INSERT INTO company_customers SELECT r.* FROM registration r WHERE ID=%s',(id_val))
    cur.execute('DELETE FROM registration WHERE ID=%s',(id_val))
    flash("Customer Registered Successfully !!","success")
    mysql.connection.commit()
    cur.close()
    return redirect(url_for('pending_registration'))

@app.route('/reject/<string:id_val>',methods=['POST','GET'])
@is_logged_in
def reject(id_val):
    cur = mysql.connection.cursor()
    cur.execute('DELETE FROM registration WHERE ID=%s',(id_val))
    flash("Customer Rejected !!","danger")
    mysql.connection.commit()
    cur.close()
    return redirect(url_for('pending_registration'))

# Registered Customers
@app.route('/registered')
@is_logged_in
def registered_customers():
    cur = mysql.connection.cursor()
    result = cur.execute('SELECT * from company_customers')
    data = cur.fetchall()
    if result>0:
        return render_template('dashboard.html', customers=data)
    else:
        return render_template('dashboard.html',msg='No customers')
    cur.close()

# Warehouse
class Add_Warehouse(Form):
    product_name = StringField('Name',[validators.Length(min=5,max=20), validators.DataRequired()])
    product_qty = IntegerField('Quantity',[validators.DataRequired()])
    product_price = DecimalField('Price',[validators.DataRequired()])

@app.route('/add_warehouse',methods=['GET','POST'])
def add_warehouse():
    form1 = Add_Warehouse(request.form)
    if request.method == 'POST' and form1.validate():
        product_name = form1.product_name.data
        product_qty = form1.product_qty.data
        product_price = form1.product_price.data

        cur = mysql.connection.cursor()
        cur.execute('INSERT INTO company_warehouse(PRODUCT_NAME,QTY,PRICE_PER_UNIT) VALUES(%s,%s,%s)',(product_name,product_qty,product_price))
        mysql.connection.commit()
        cur.close()
        flash('Product Added !!','success')
        return redirect(url_for('dashboard'))
    return render_template('dashboard.html',form1=form1)

# Show Warehouse stocks
@app.route('/show_stocks')
@is_logged_in
def show_stocks():
    cur = mysql.connection.cursor()
    result = cur.execute('SELECT * from company_warehouse')
    data = cur.fetchall()
    if result>0:
        return render_template('dashboard.html', stocks=data)
    else:
        msg = 'No Pending registration'
        return render_template('dashboard.html',msg=msg)
    cur.close()

这是我的 app.py
。的方法pending_registration()registered_customers()show_stocks()需要在点击每次的相应标签来进行查看。

<div class="tab">
      <button class="tablinks" href="{{url_for('pending_registration')}}" onclick="opentab(event, 'pending_user_registration')">Pending User Registration</button>
      <button class="tablinks" href="/show_stocks" onclick="opentab(event, 'warehouse')">Warehouse</button>
      <button class="tablinks" href="{{url_for('registered_customers')}}" onclick="opentab(event, 'registered-customer')">Registered Customer</button>
      <button class="tablinks" href="#" onclick="opentab(event, 'settings')">Settings</button>
    </div>
    <div id="pending_user_registration" class="tabcontent">
        <h2 class="d-flex justify-content-center">Pending User Registration</h2>
        {% include 'includes/_messages.html' %}
        <table class="table table-hover table-sm">
          <thead class="alert-primary">
            <tr>
              <th scope="col">#</th>
              <th scope="col">Name</th>
              <th scope="col">Category</th>
              <th scope="col">Email Id</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {% for row in users %}
            <tr>
              <th scope="row">{{loop.index}}</th>
              <td>{{row.NAME}}</td>
              <td>{{row.CATEGORY}}</td>
              <td>{{row.EMAIL}}</td>
              <td>
                <a href="/accept/{{row.ID}}" class="btn btn-success btn-sm">Accept</a>
                <a href="/reject/{{row.ID}}" class="btn btn-danger btn-sm">Reject</a>
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
    </div>
    <div id="warehouse" class="tabcontent" style="display: none;">
      <h2 class="d-flex justify-content-center">Warehouse</h2>
      <a href="/add_warehouse" class="btn btn-info btn-sm mb-2" data-toggle="modal" data-target="#add-warehouse-product">Add Product</a>    
      <table class="table table-bordered table-sm bg-light">
          <thead>
            <tr>
              <th scope="col">PId</th>
              <th scope="col">Name</th>
              <th scope="col">Quantity</th>
              <th scope="col">Price</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {% for stock in stocks %}
            <tr>
              <th scope="row">stock.cpID</th>
              <td>row.PRODUCT_NAME</td>
              <td>row.QTY</td>
              <td>row.PRICE_PER_UNIT</td>
              <td>
                <a href="#" class="btn btn-warning btn-sm">Update</a>
                <a href="#" class="btn btn-danger btn-sm">Delete</a>
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
    </div>
    <div id="registered-customer" class="tabcontent" style="display: none;">
        <h2 class="d-flex justify-content-center">Registered Customer</h2>
        {% include 'includes/_messages.html' %}
        <table class="table table-bordered table-sm">
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">Name</th>
              <th scope="col">Email Id</th>
              <th scope="col">Category</th>
            </tr>
          </thead>
          <tbody>
            {% for row in customers %}
            <tr>
              <th scope="row">{{loop.index}}</th>
              <td>{{row.NAME}}</td>
              <td>{{row.EMAIL}}</td>
              <td>{{row.CATEGORY}}</td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
    </div>
</div>

This is the html part.
How can I get my required output ?

问题答案:

我可以找到两种方法来显示选项卡:1.使用Ajax并嵌入HTML 2.通过继承子布局中的布局使用页面加载

1.使用Ajax(我正在使用JQuery Ajax)

// Python
@app.route('/get-tab/<int:id>')
def get_tab(id):
    return render_template('tab-template.html')

// View
 {% extends 'layout/base.html' %}

 {% block content %}
     <button class="btn btn-primary btn-sm" onclick="loadPage(1)">First</button>
     <button class="btn btn-default btn-sm" onclick="loadPage(2)">Second</button>
     <div id="display"></div>
     <script>
         function loadPage(id) {
             $.ajax({
               type: 'GET',
                url: '/get-tab/' + id,
                success: function (e) {
                   $('#display').html(e);                                                                                                                                                                   
                }
             });
         }
     </script>
  {% endblock %}

演示:http//phearaeun.pythonanywhere.com/child

2.继承基础布局到子布局

--> Base Layout
    --> Child layout
        --> Template

// Base Layout
...

{% block content %}{% endblock %}

...

// Child layout to inherit base layout
...
{% extends 'layout/base.html' %}
{% block content %}
   // Header content
   {% block subcontent %}{% endblock %}
{% endblock %}
...

// Template to inherit child layout
...
{% extends 'layout/child.html' %}
{% block subcontent %}

{% endblock %}