【问题标题】:How to call multiple routes inside one route?如何在一条路线中调用多条路线?
【发布时间】:2019-09-20 02:13:30
【问题描述】:

我有一个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 ?

【问题讨论】:

    标签: python mysql flask jinja2


    【解决方案1】:

    我可以找到两种方法来显示标签: 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 %}
    

    【讨论】:

    • 这意味着如果我遵循流程 2,我必须为每个函数创建 .html 文件,然后在该 div 中继承它对吗?
    • 进程 2 带有刷新页面。如果您更喜欢 1,则必须创建一个路由并处理来自您的选项卡单击或多个路由的参数。
    • 我有一个问题,因为我对 AJAX 了解不多。如何从单个 div 调用 div 的 3 个不同视图
    • 你可以在这里查看我的例子repl.it/@chheunpheara/base-and-child-layout
    • 以上链接的示例使用 1 条路由来处理来自选项卡单击的不同值(参数)。因此,您仍然可以使用不同的选项卡内容留在同一页面上。我不会用 jQuery ajax 写,因为答案中有演示链接。
    猜你喜欢
    • 1970-01-01
    • 2016-01-09
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多