问题
in my Flask Project i have configured a basepage.html
Jinja template every other page inherits from.
In this basepage.html
i want to have a Search bar at the top, so that it also appears at every page inheriting from it.
The input from this search form (is a form even the best way to do it?) should be processed
by the routing function search()
I defined as follows:
views.py
@app.route('/')
@app.route('/dashboard')
def dashboard():
return render_template('Dashboard.html') #Dashboard.html inherits from basepage.html
@app.route('/search', methods=['GET' ,'POST'])
def search():
search_query = #input from search-bar
result = #get data matching search_query from database
return render_template('Search.html', results = results) #Search.html extends basepage.html
forms.py excerpt:
class Search(FlaskForm):
search_query = StringField('Search for ...')
submit = SubmitField('Search')
Is there a way i can have my Search form on every page, so when i enter my query in the bar at the top of the Dashboard form and press enter the search_query gets processed by the search()
view?
回答1:
Just create your searchbar template code in a partial file located at /templates/includes/my_searchbar.html
or whatever you want to name it and then in your base template just place an includes directive wherever you want the search to render in, something like:
{% include 'includes/my_searchbar.html' %}
If the searchbar is included in base and all your other templates inherit from base, then search will be included on all pages.
All of your routes will also need to have the Search() form class included so they have access to the form, so you will need to modify your routes something like:
from app.forms import Search #if you defined Search in /app/forms.py
@app.route('/dashboard')
def dashboard():
search_form = Search() #initialize an instance of the form
return render_template('Dashboard.html', search_form=search_form)
Then you can use search_form
in your includes/my_searchbar.html
partial to render the form. Maybe something like:
<form class="form" method="post" role="form">
{{ search_form.hidden_tag() }}
{{ search_form.search_query }}
{{ search_form.submit }}
</form>
来源:https://stackoverflow.com/questions/62094647/flaskwtf-same-form-on-every-view-page