使用Flask的`render_template()`传递参数。

huangapple go评论72阅读模式
英文:

Passing parameters with flask render_template()

问题

我需要显示一些选择选项。一旦选择了类别,我希望显示另一个选择框来选择子类别。

我的Flask代码

def return_panim():
    panim = ["", "טיפול ניקוי עמוק", "טיפול יופי", "טיפול פילינג עמוק", "טיפול לאקנה ולעור בעייתי", "טיפול אנטי אייג'ינג מזוטרפיה", "טיפול אנטי אייג'ינג מיצוק העור"]
    data = """
        <label>קטגוריה</label>
        <select id="subCategory" onchange="loadDoc()">"""
    for pan in panim:
        data = data + f'<option value="{pan}">{pan}</option>'
    data = data + '</select>'
    return data


def return_categories():
    category_list = ["", "טיפול פנים", "טיפול הסרת שיער", "טיפול הסרת פיגמנטציה", "עיצוב גבות", "מניקור", "פדיקור", "שעווה", "שעווה גברים"]
    data = """
        <label>תת קטגוריה</label>
        <select id="category" onchange="loadDoc()">"""
    for category in category_list:
        data = data + f'<option value="{category}">{category}</option>'
    data = data + '</select>'    
    return data

@app.route("/appoint", methods=["GET", "POST"])
def apple(name=None):
    if request.method == "POST":
        r = request.get_data().decode("utf-8")
        print(r)
        if r ==  "טיפול פנים":
            print(return_panim())
            return render_template("appoint.html",  data_category=return_categories(), data_subcategory=return_panim())
    return render_template("appoint.html",  data_category=return_categories())

我的客户端代码

<html>
<head>
</head>
<body>
{{ data_category | safe }}
{{ data_subcategory | safe }}
<script>
  function loadDoc() {
    let encoder = new TextEncoder();
  const xhttp = new XMLHttpRequest();
  var sel = document.getElementById("category");
  var text = sel.value;
  xhttp.open("POST", "https://www.annastudio.beauty/appoint", true);
  xhttp.send(encoder.encode(text));
}
</script>
</body>
</html>

当我尝试在没有条件的情况下返回时,像这样

@app.route("/appoint", methods=["GET", "POST"])
def apple(name=None):
    return render_template("appoint.html",  data_category=return_categories(), data_subcategory=return_panim())

它会呈现两个选择框。

英文:

I need to display some select options. Once the category is chosen, I want to display the subcategory with another select.

My flask code

def return_panim():
    panim = [&quot;&quot;, &quot;טיפול ניקוי עמוק&quot;, &quot;טיפול יופי&quot;, &quot;טיפול פילינג עמוק&quot;, &quot;טיפול לאקנה ולעור בעייתי&quot;, &quot;טיפול אנטי אייג&#39;ינג מזוטרפיה&quot;, &quot;טיפול אנטי אייג&#39;ינג מיצוק העור&quot;]
    data = &quot;&quot;&quot;
        &lt;label&gt;קטגוריה&lt;/label&gt;
        &lt;select id=&quot;subCategory&quot; onchange=&quot;loadDoc()&quot;&gt;&quot;&quot;&quot;
    for pan in panim:
        data = data + &#39;&lt;option value=&#39; + &#39;&quot;&#39; + pan + &#39;&quot;&#39; + &quot;&gt;&quot; + &#39;&quot;&#39; + pan + &#39;&quot;&#39; + &#39;&lt;/option&gt;&#39;
    data = data + &#39;&lt;/select&gt;&#39;
    return data


def return_categories():
    category_list = [&quot;&quot;, &quot;טיפול פנים&quot;, &quot;טיפול הסרת שיער&quot;, &quot;טיפול הסרת פיגמנטציה&quot;, &quot;עיצוב גבות&quot;, &quot;מניקור&quot;, &quot;פדיקור&quot;, &quot;שעווה&quot;, &quot;שעווה גברים&quot;]
    data = &quot;&quot;&quot;
        &lt;label&gt;תת קטגוריה&lt;/label&gt;
        &lt;select id=&quot;category&quot; onchange=&quot;loadDoc()&quot;&gt;&quot;&quot;&quot;
    for category in category_list:
        data = data + &#39;&lt;option value=&#39; + &#39;&quot;&#39; + category + &#39;&quot;&#39; + &#39;&gt;&#39; + category + &#39;&lt;/option&gt;&#39;
    data = data + &quot;&lt;/select&gt;&quot;    
    return data

@app.route(&quot;/appoint&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])
def apple(name=None):
    if request.method == &quot;POST&quot;:
        r = request.get_data().decode(&quot;utf-8&quot;)
        print(r)
        if r ==  &quot;טיפול פנים&quot;:
            print(return_panim())
            return render_template(&quot;appoint.html&quot;,  data_category=return_categories(), data_subcategory=return_panim())
    return render_template(&quot;appoint.html&quot;,  data_category=return_categories())

My client side

&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
{{ data_category | safe }}
{{ data_subcategory | safe }}
&lt;script&gt;
  function loadDoc() {
    let encoder = new TextEncoder();
  const xhttp = new XMLHttpRequest();
  var sel = document.getElementById(&quot;category&quot;);
  var text = sel.value;
  xhttp.open(&quot;POST&quot;, &quot;https://www.annastudio.beauty/appoint&quot;, true);
  xhttp.send(encoder.encode(text));
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

When I try to return without condition like so

@app.route(&quot;/appoint&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])
def apple(name=None):
    return render_template(&quot;appoint.html&quot;,  data_category=return_categories(), data_subcategory=return_panim())

It renders both selects.

答案1

得分: 1

我不认为你必须为此任务使用Ajax。

以下示例使用了两个字段集。第二个字段集是根据第一个选择元素中的选择而使用JavaScript启用或禁用的。禁用的字段集使用CSS进行隐藏。

如果您不想使用字段集,您可以以相同的方式禁用和启用单个输入字段。

from enum import Enum, unique
from flask import (
	Flask, 
	redirect, 
	render_template, 
	request
)

@unique 
class Categories(str, Enum):
	OPTION1 = "טיפול פנים"
	OPTION2 = "טיפול הסרת שיער"
	OPTION3 = "טיפול הסרת פיגמנטציה"
	OPTION4 = "עיצוב גבות"
	OPTION5 = "מניקור"
	OPTION6 = "פדיקור"
	OPTION7 = "שעווה"
	OPTION8 = "שעווה גברים"

@unique 
class SubCategories(str, Enum):
	OPTION1 = "טיפול ניקוי עמוק"
	OPTION2 = "טיפול יופי"
	OPTION3 = "טיפול פילינג עמוק"
	OPTION4 = "טיפול לאקנה ולעור בעייתי"
	OPTION5 = "טיפול אנטי אייג'ינג מזוטרפיה"
	OPTION6 = "טיפול אנטי אייג'ינג מיצוק העור"

app = Flask(__name__)

@app.route('/appoint', methods=['GET', 'POST'])
def appoint():
	if request.method == 'POST':
		category = request.form.get('category', Categories.OPTION1, type=lambda x: Categories[x])
		subcategory = request.form.get('subcategory', type=lambda x: SubCategories[x])
		print(category.value)
		print(subcategory and subcategory.value)
		return redirect(request.url)
	return render_template(
		'appoint.html', 
		categories=Categories, 
		subcategories=SubCategories
	)
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Appoint</title>
	<style>
		fieldset[disabled] {
			display: none;
		}
	</style>
</head>
<body>
	
	<form method="post">
		<fieldset name="basics">
			<label for="category">Category</label>
			<select name="category" id="category">
				{% for cat in categories -%}
				<option value="{{ cat.name }}">{{ cat.value }}</option>
				{% endfor -%}
			</select>
		</fieldset>
		<fieldset name="extended">
			<label for="subcategory">Subcategory</label>
			<select name="subcategory" id="subcategory">
				{% for cat in subcategories -%}
				<option value="{{ cat.name }}">{{ cat.value }}</option>
				{% endfor -%}
			</select>
		</fieldset>
		<button type="submit">Submit</button>
	</form>

	<script>
		(function() {

			const triggerVal = {{ categories.OPTION1.name | tojson }};
			const selectElem = document.getElementById('category');
			const fieldsetElem = document.querySelector('fieldset[name="extended"]');
			selectElem.addEventListener('change', function() {
				fieldsetElem.disabled = this.value !== triggerVal;
			});

		})();
	</script>
</body>
</html>
英文:

I don't think you have to use Ajax for this task.

The following example uses two field sets. The second field set is enabled or disabled with JavaScript depending on the selection made in the first select element. A disabled field set is hidden using CSS.

If you don't want to use a field set, you can disable and enable individual input fields in the same way.

from enum import Enum, unique
from flask import (
	Flask, 
	redirect, 
	render_template, 
	request
)

@unique 
class Categories(str, Enum):
	OPTION1 = &quot;טיפול פנים&quot;
	OPTION2 = &quot;טיפול הסרת שיער&quot;
	OPTION3 = &quot;טיפול הסרת פיגמנטציה&quot;
	OPTION4 = &quot;עיצוב גבות&quot;
	OPTION5 = &quot;מניקור&quot;
	OPTION6 = &quot;פדיקור&quot;
	OPTION7 = &quot;שעווה&quot;
	OPTION8 = &quot;שעווה גברים&quot;

@unique 
class SubCategories(str, Enum):
	OPTION1 = &quot;טיפול ניקוי עמוק&quot;
	OPTION2 = &quot;טיפול יופי&quot;
	OPTION3 = &quot;טיפול פילינג עמוק&quot;
	OPTION4 = &quot;טיפול לאקנה ולעור בעייתי&quot;
	OPTION5 = &quot;טיפול אנטי אייג&#39;ינג מזוטרפיה&quot;
	OPTION6 = &quot;טיפול אנטי אייג&#39;ינג מיצוק העור&quot;

app = Flask(__name__)

@app.route(&#39;/appoint&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])
def appoint():
	if request.method == &#39;POST&#39;:
		category = request.form.get(&#39;category&#39;, Categories.OPTION1, type=lambda x: Categories[x])
		subcategory = request.form.get(&#39;subcategory&#39;, type=lambda x: SubCategories[x])
		print(category.value)
		print(subcategory and subcategory.value)
		return redirect(request.url)
	return render_template(
		&#39;appoint.html&#39;, 
		categories=Categories, 
		subcategories=SubCategories
	)
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;meta charset=&quot;utf-8&quot;&gt;
	&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
	&lt;title&gt;Appoint&lt;/title&gt;
	&lt;style&gt;
		fieldset[disabled] {
			display: none;
		}
	&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
	
	&lt;form method=&quot;post&quot;&gt;
		&lt;fieldset name=&quot;basics&quot;&gt;
			&lt;label for=&quot;category&quot;&gt;Category&lt;/label&gt;
			&lt;select name=&quot;category&quot; id=&quot;category&quot;&gt;
				{% for cat in categories -%}
				&lt;option value=&quot;{{ cat.name }}&quot;&gt;{{ cat.value }}&lt;/option&gt;
				{% endfor -%}
			&lt;/select&gt;
		&lt;/fieldset&gt;
		&lt;fieldset name=&quot;extended&quot;&gt;
			&lt;label for=&quot;subcategory&quot;&gt;Subcategory&lt;/label&gt;
			&lt;select name=&quot;subcategory&quot; id=&quot;subcategory&quot;&gt;
				{% for cat in subcategories -%}
				&lt;option value=&quot;{{ cat.name }}&quot;&gt;{{ cat.value }}&lt;/option&gt;
				{% endfor -%}
			&lt;/select&gt;
		&lt;/fieldset&gt;
		&lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
	&lt;/form&gt;

	&lt;script&gt;
		(function() {

			const triggerVal = {{ categories.OPTION1.name | tojson }};
			const selectElem = document.getElementById(&#39;category&#39;);
			const fieldsetElem = document.querySelector(&#39;fieldset[name=&quot;extended&quot;]&#39;);
			selectElem.addEventListener(&#39;change&#39;, function() {
				fieldsetElem.disabled = this.value !== triggerVal;
			});

		})();
	&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

huangapple
  • 本文由 发表于 2023年3月4日 02:53:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定