React和Flask-Restful-如何渲染Jinja模板

时间:2019-05-27 16:19:48

标签: reactjs axios jinja2 flask-restful

我正在使用前端的React构建RESTful Flask API。

我希望能够使用React来获取和上传数据,但是首先要在Flask的服务器端渲染我的Jinja模板。这是我到目前为止的内容:


反应

Seeds.jsx

import React, { Component } from 'react';
import axios from 'axios';

class Seeds extends Component{
  constructor (props) {
    super(props);
    this.state = {
      restaurant:'',      
      email: '',
      id: '',
      username: '',
      active: '',
      admin: ''    
    };
  };
  componentDidMount() {
    if (this.props.isAuthenticated) {
      this.getSeeds();
    }
  };
  getSeeds(event) {
    const options = {
      url: `${process.env.REACT_APP_WEB_SERVICE_URL}/seeds`,
      method: 'get',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.authToken}`
      }
    };
    return axios(options)
    .then((res) => {
    console.log(res)  
      console.log(res.data.data) 
      this.setState({
        restaurant: res.data.data[0].restaurant,
        template: res.data.data[0].content
      })
    })
    .catch((error) => { console.log(error); });
  };

    render(){
        let seeds_page;
        seeds_page = this.setState.template;

        return (
           <div className="form">
            {seeds_page}
           </div>
        );
    }
}

export default Seeds;

烧瓶

seeds.py

seeds_bp = Blueprint('seeds', 
                     __name__, 
                     template_folder='templates', 
                     static_url_path='static') 

@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():

    user = User.query.filter_by(id=1).first()

    response_object = {
          'status': 'success',
          'message': 'success',
          'data': [{"user": user.restaurant,
                    "content": "seeds.html"}]
    }        
    return jsonify(response_object), 200

Jinja

seeds.html

{% include 'partials/head.html' %}
<section id="woz-content" >

  <div class="container">
    <h1 class="page-title">Menu(edit)</h1>
  </div>

  <div class="container">

    <h2 class="page-title">Seeds</h2>

    <ul style="list-style:none" >
        <li><form action="{{ url_for('seeds.handle_seeds') }}"method="post">Seed1
            <input type="text" name="seed1"/>
            <label style="font-size: 11px;"></label>  
            <input type="submit" value="seed" >
          </form>
        </li>
       <li><form action="{{ url_for('seeds.handle_seeds') }}" method="post">Seed2
            <input type="text" name="seed2"/>
            <label style="font-size: 11px;"></label>
            <input type="submit" value="seed" >
          </form></li>
     </ul>
   </div>

我设法获取数据,但未进行任何渲染。

如何调整代码以在获取数据时呈现模板?

1 个答案:

答案 0 :(得分:0)

我假设您想在react组件中呈现seed.html,因为您在react组件中包含以下代码:

render(){
        let seeds_page;
        seeds_page = this.setState.template;

        return (
           <div className="form">
            {seeds_page}
           </div>
        );
    }

要实现此操作,您需要确保您的seed.html文件具有与JSX相同的语法。例如,此代码在您的react组件中不起作用:

<h1 class='title'>Some title</h1>

因为react使用className而不是class。因此,您需要重写您的seed.html以使其类似于JSX语法,或者找到react模块可以将html模板解析为JSX代码。它将类似于:

{% include 'partials/head.html' %}
<section id="woz-content" >

  <div className="container">
    <h1 className="page-title">Menu(edit)</h1>
  </div>
  ...
</section>

然后,您可以使用render_template函数渲染模板:

from flask import render_template
@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():

    user = User.query.filter_by(id=1).first()
    example = "some example"
    template = render_template('seeds.html', example=example)

    response_object = {
          'status': 'success',
          'message': 'success',
          'data': [{"user": user.restaurant,
                    "content": template}]
    }        
    return jsonify(response_object)

然后,您可以通过axios请求获取模板并保存为模板状态。要将模板字符串转换为react组件,可以使用React HTML Parser实用程序将HTML字符串转换为React组件。 因此Seeds.jsx将类似于以下内容:

import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 }
from 'react-html-parser';

class Seeds extends Component{
    // ... 
    render(){
        seeds_page = this.state.template;

        return (
           <div className="form">
            { ReactHtmlParser(seeds_page) }
           </div>
        );
    }
}

export default Seeds;