jinja2 相关问题

Jinja2是Python的快速模板引擎。它具有完整的Unicode支持,自动转义,继承,宏和许多其他功能。

通过循环创建按钮时如何单独控制按钮

我正在使用 jinja2 在 Flask 中创建一个管理页面。登录后,管理员可以看到用户发送的各种查询,并据此采取行动。使用 jinja 模板我检索了 da...

回答 1 投票 0

使用 Ansible playbook 和自定义 value.yaml 部署 Helm 图表

我正在尝试使用 Ansible playbook 将带有自定义 value.yaml 文件的 ArgoCD Helm 图表部署到 Kubernetes 集群中 这是我正在使用的代码 - 名称:在 argocd 命名空间内部署 ArgoCD 图表...

回答 1 投票 0

如何在 Ansible 中对版本号进行排序

我正在构建一个 Ansible 剧本,我想在其中备份数据库,以备需要升级软件时使用。为此,我想比较可用的最高版本号

回答 4 投票 0

迭代 DBT 中的所有行和列 - Jinja

我有一张看起来像这样的桌子: ID 姓名 表名 聚合类型 聚合列 条件,独特 1 课程数 stg_课程 数数 无效的 无效的 2 捆绑数 stg_bundles 数数 无效的 努...

回答 3 投票 0

dbt 文档未生成有关 dbt 测试的文档

我正在尝试提供 dbt 测试的文档。 我创建了一个验证 2 个数字之和的测试(当然,这只是一个示例)。 {% 测试 test_sum(summand_a, summand_b, 总计) %} 东南...

回答 1 投票 0

Superset启用jinja

我需要在 Superset 中启用 jinja。 我发现我必须将 ENABLE_TEMPLATE_PROCESSING 设置为 true。我在 config.py 中发现它的默认值为 false。但也有人说...

回答 1 投票 0

Django 和 Jinja2 模板使用 {{ url() }}

我正在尝试弄清楚如何使用 jinja 的 {{ url() }} 在我的 html 中传递我的 user_id,使用不需要任何 id(如 /dashboard/ )的 url 工作正常,但我需要将 id 传递给这个-示例:/u...

回答 3 投票 0

Ansible 将变量传递给 j2 模板

使用ansible,我使用j2模板来替换文件,并传递每个环境特有的环境变量和一些共享的环境变量。全局或局部工作的变量都不是。我有以下...

回答 1 投票 0

如何检查dbt中的表是否为空?

尝试了以下两种方法来检查表是否为空。必须根据表是否为空来运行 if 部分或 else 部分 方法 1:尝试了此方法,即使表 XYZ 中有行,下面也会打印 a (

回答 1 投票 0

如何在 jinja2 模板中将字符串转换为日期时间对象

如何将 jinja2 模板内的字符串转换为日期时间对象? 我想做类似下面的事情,但 strptime 不被识别。 {% set dtime=strptime(passedintime, '%H:%M:%S...

回答 1 投票 0

使用 jinja2 动态更改 Excel 模板中的公式?

我正在寻找一种将 pandas 数据框填充到给定 Excel 模板中的方法(保留所有格式)。我偶然发现了以下有趣的博客文章,在 Excel 中使用 jinja2 模板......

回答 1 投票 0

TemplateResponse 上下文数据在 POST 请求后未显示在模板中

在 POST 请求之后,我尝试在模板上显示一些数据。我还不明白为什么它不显示。 home.jinja 模板 在 POST 请求之后,我尝试在模板上显示一些数据。我还不明白为什么它不显示。 home.jinja模板 <section class="order-interface"> <div class="order-parameters"> <form method="POST" action="{{ url_for('generate_meal_recipe')}}" id="order-form"> <label for="cuisineType">Choose your preferred cuisine(s) if any:</label><br> <input type="checkbox" name="cuisineType" value="american"> 🇺🇸 American<br> <input type="checkbox" name="cuisineType" value="asian"> 🌏 Asian<br> <input type="checkbox" name="cuisineType" value="british"> 🇬🇧 British<br> <input type="checkbox" name="cuisineType" value="caribbean"> 🌴 Caribbean<br> <input type="checkbox" name="cuisineType" value="central europe"> 🇪🇺 Central Europe<br> <input type="checkbox" name="cuisineType" value="chinese"> 🇨🇳 Chinese<br> <input type="checkbox" name="cuisineType" value="eastern europe"> 🇪🇺 Eastern Europe<br> <input type="checkbox" name="cuisineType" value="french"> 🇫🇷 French<br> <input type="checkbox" name="cuisineType" value="indian"> 🇮🇳 Indian<br> <input type="checkbox" name="cuisineType" value="italian"> 🇮🇹 Italian<br> <input type="checkbox" name="cuisineType" value="japanese"> 🇯🇵 Japanese<br> <input type="checkbox" name="cuisineType" value="kosher"> 🕍 Kosher<br> <input type="checkbox" name="cuisineType" value="mediterranean"> 🌊 Mediterranean<br> <input type="checkbox" name="cuisineType" value="mexican"> 🇲🇽 Mexican<br> <input type="checkbox" name="cuisineType" value="middle eastern"> 🌍 Middle Eastern<br> <input type="checkbox" name="cuisineType" value="nordic"> ❄️ Nordic<br> <input type="checkbox" name="cuisineType" value="south american"> 🌎 South American<br> <input type="checkbox" name="cuisineType" value="south east asian"> 🌏 South East Asian<br> <input type="checkbox" name="cuisineType" value="world"> 🌍 World<br> <label for="mealType">Choose the type of meal:</label><br> <select name="mealType" id="mealType"> <option value="breakfast">Breakfast</option> <option value="brunch">Brunch</option> <option value="dinner">Dinner</option> <option value="snack">Snack</option> <option value="teatime">Teatime</option> </select> <label for="diet">Choose your diet if any:</label><br> <input type="checkbox" name="diet" value="balanced"> 🌿 Balanced<br> <input type="checkbox" name="diet" value="high-fiber"> 🌾 High Fiber<br> <input type="checkbox" name="diet" value="high-protein"> 🥩 High Protein<br> <input type="checkbox" name="diet" value="low-carb"> 🥦 Low Carb<br> <input type="checkbox" name="diet" value="low-fat"> 🍎 Low Fat<br> <input type="checkbox" name="diet" value="low-sodium"> 🧂 Low Sodium<br> <label for="health">Choose your health preferences if any:</label><br> <input type="checkbox" name="health" value="alcohol-cocktail"> 🍹 Alcohol Cocktail<br> <input type="checkbox" name="health" value="alcohol-free"> 🚱 Alcohol Free<br> <input type="checkbox" name="health" value="celery-free"> 🌱 Celery Free<br> <input type="checkbox" name="health" value="crustacean-free"> 🦀 Crustacean Free<br> <input type="checkbox" name="health" value="dairy-free"> 🥛 Dairy Free<br> <input type="checkbox" name="health" value="DASH"> DASH<br> <input type="checkbox" name="health" value="egg-free"> 🥚 Egg Free<br> <input type="checkbox" name="health" value="fish-free"> 🐟 Fish Free<br> <input type="checkbox" name="health" value="fodmap-free"> FODMAP Free<br> <input type="checkbox" name="health" value="gluten-free"> 🌾 Gluten Free<br> <input type="checkbox" name="health" value="immuno-supportive"> Immuno Supportive<br> <input type="checkbox" name="health" value="keto-friendly"> Keto Friendly<br> <input type="checkbox" name="health" value="kidney-friendly"> Kidney Friendly<br> <input type="checkbox" name="health" value="kosher"> 🕍 Kosher<br> <input type="checkbox" name="health" value="low-fat-abs"> Low Fat Abs<br> <input type="checkbox" name="health" value="low-potassium"> Low Potassium<br> <input type="checkbox" name="health" value="low-sugar"> Low Sugar<br> <input type="checkbox" name="health" value="lupine-free"> Lupine Free<br> <input type="checkbox" name="health" value="Mediterranean"> 🌊 Mediterranean<br> <input type="checkbox" name="health" value="mollusk-free"> Mollusk Free<br> <input type="checkbox" name="health" value="mustard-free"> Mustard Free<br> <input type="checkbox" name="health" value="no-oil-added"> No Oil Added<br> <input type="checkbox" name="health" value="paleo"> 🦴 Paleo<br> <input type="checkbox" name="health" value="peanut-free"> 🥜 Peanut Free<br> <input type="checkbox" name="health" value="pescatarian"> Pescatarian<br> <input type="checkbox" name="health" value="pork-free"> Pork Free<br> <input type="checkbox" name="health" value="red-meat-free"> Red Meat Free<br> <input type="checkbox" name="health" value="sesame-free"> Sesame Free<br> <input type="checkbox" name="health" value="shellfish-free"> Shellfish Free<br> <input type="checkbox" name="health" value="soy-free"> Soy Free<br> <input type="checkbox" name="health" value="sugar-conscious"> Sugar Conscious<br> <input type="checkbox" name="health" value="sulfite-free"> Sulfite Free<br> <input type="checkbox" name="health" value="tree-nut-free"> 🌰 Tree Nut Free<br> <input type="checkbox" name="health" value="vegan"> 🌱 Vegan<br> <input type="checkbox" name="health" value="vegetarian"> 🥕 Vegetarian<br> <input type="checkbox" name="health" value="wheat-free"> 🌾 Wheat Free<br> <input type="submit" value="Submit"> </form> </div> {% if recipe %} <div>{{recipe}}</div> {% endif %} </section> script.js document .getElementById("order-form") .addEventListener("submit", function (event) { event.preventDefault(); let q = document.getElementById("q").value; // Convert selected checkboxes to list // cuisineType let cuisineType_checkboxes = document.getElementsByName("cuisineType"); let cuisineType = Array.from(cuisineType_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); // mealType let mealType = [document.getElementById("mealType").value]; // diet let diet_checkboxes = document.getElementsByName("diet"); let diet = Array.from(diet_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); // health let health_checkboxes = document.getElementsByName("health"); let health = Array.from(health_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); let form_data = { q: q, cuisineType: cuisineType, mealType: mealType, diet: diet, health: health, }; // Send the data to the server fetch("/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(form_data), }) .then((response) => response.text()) .then((data) => { console.log(data); document.getElementById("order-form").reset(); // Reset the form }) .catch((error) => console.error("Error:", error)); }); main.py from fastapi import FastAPI, Request, Response from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from typing import List, Optional app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") class Order(BaseModel): """Order object.""" q: str cuisineType: Optional[List[str]] = [] mealType: Optional[List[str]] = [] diet: Optional[List[str]] = [] health: Optional[List[str]] = [] @app.get("/") async def home(request: Request) -> Response: """Home page.""" return templates.TemplateResponse("home.jinja", {"request": request}) @app.post("/") async def generate_meal_recipe(request: Request, order: Order) -> Response: """Retrieve generated meal recipe.""" # Logic recipe = "abc" return templates.TemplateResponse("home.jinja", context={"request": request, "recipe": recipe}) 提交表单时,我应该能够在模板上看到 recipe 值 (abc)。奇怪的是,我不是。使用浏览器开发工具(检查网络)时,我找到了对请求的响应并显示了数据。为什么我没有直接看到它?和剧本有关系吗? 问题出在 JS 代码上。我正在阻止默认表单操作,只是将获取的数据记录在控制台中。通过更新页面来更新脚本可以显示数据: script.js document .getElementById("order-form") .addEventListener("submit", function (event) { event.preventDefault(); let q = document.getElementById("q").value; // Convert selected checkboxes to list // cuisineType let cuisineType_checkboxes = document.getElementsByName("cuisineType"); let cuisineType = Array.from(cuisineType_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); // mealType let mealType = [document.getElementById("mealType").value]; // diet let diet_checkboxes = document.getElementsByName("diet"); let diet = Array.from(diet_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); // health let health_checkboxes = document.getElementsByName("health"); let health = Array.from(health_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); let form_data = { q: q, cuisineType: cuisineType, mealType: mealType, diet: diet, health: health, }; // Send the data to the server fetch("/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(form_data), }) .then((response) => response.text()) .then((data) => { console.log(data); document.getElementById("order-form").reset(); // Reset the form // Update the whole page with the new data document.open(); document.write(data); document.close(); }) .catch((error) => console.error("Error:", error)); }); 另一种方法是直接使用 FastApi 与 Request 对象的依赖关系来重新格式化我正在使用脚本执行的表单字段。它看起来像这样: main.py from fastapi import FastAPI, Request, Response, Depends from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from typing import List, Optional, Annotated app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") class Order(BaseModel): """Order object.""" q: str cuisineType: Optional[List[str]] = [] mealType: Optional[List[str]] = [] diet: Optional[List[str]] = [] health: Optional[List[str]] = [] @app.get("/") async def home(request: Request) -> Response: """Home page.""" return templates.TemplateResponse("home.jinja", {"request": request}) async def reformat_form_fields(request: Request): """Reformat submitted form fields so it could comply with API parameters type.""" async with request.form() as form: q = form.get("q") cuisineType = form.getlist("cuisineType") if "cuisineType" in form else [] mealType = form.getlist("mealType") if "mealType" in form else [] diet = form.getlist("diet") if "diet" in form else [] health = form.getlist("health") if "health" in form else [] order = Order(q=q, cuisineType=cuisineType, mealType=mealType, diet=diet, health=health) return order @app.post("/") async def generate_meal_recipe( request: Request, order: Annotated[Order, Depends(reformat_form_fields)] ) -> Response: """Retrieve generated meal recipe.""" # Logic recipe = "abc" return templates.TemplateResponse("home.jinja", context={"request": request, "recipe": recipe})

回答 1 投票 0

将列表中的 2 个字典元素加入到 1 个中不起作用

我正在从前一个任务的 json 结果列表中提取数据,以根据子网获取 VLAN 编号。 使用这个我需要一个包含两个 vlan 的列表,其形式为: “nic1”:[&

回答 1 投票 0

Jinja2 复选框值在烧瓶形式中返回为“on”

我有一个仪表板,用户可以在其中从可用电影类型列表中进行选择。他们还可以选择电影播放时间。当查看控制台时,看起来这些值正在“发布...

回答 1 投票 0

views 在创建 post 方法之前从模板中获取值

我正在创建一款奇怪的游戏。基本上,用户会看到四张图片,其中一张是奇数图片,当用户选择奇数图片时,分数会增加 1。我遇到的问题是我正在发送...

回答 1 投票 0

使用 Jinja 迭代引导卡

我正在尝试使用 Jinja 从 Bootstrap 迭代卡片组内的卡片,因此 1 组内的卡片不超过 4 张,但我最终以 1 张卡片并排完成。这是我的代码: {% 设置 n ...

回答 1 投票 0

烧瓶重定向后字母无法正确显示

实时站点:https://charlie-project3-aebf005f6451.herokuapp.com/viewlib 仓库:https://github.com/Tropicalbunny/FLASK 我遇到一个问题,我的刽子手页面没有显示显示的字母...

回答 1 投票 0

Flask:如何修复构建 URL 端点时的构建错误

我正在尝试运行我的 Flask 应用程序,该应用程序以前可以正常工作,但现在抛出错误 werkzeug.routing.exceptions.BuildError:无法为端点“dataVis”构建 url。您的意思是“静态”吗

回答 1 投票 0

Jinja2 模板预编译有什么故事?

https://github.com/pallets/jinja 说: 模板即时编译为优化的 Python 代码并缓存,也可以提前编译。 听起来不错,我想将我的网站部署到 AWS

回答 1 投票 0

ansible / jinja,如果两个字典列表中的一个键值匹配,则将一个字典列表中的键值添加到另一个字典列表中

我正在尝试从一个字典列表中获取键值,然后将它们插入到另一个字典列表上的字典中,如果其中一个键与 jinja 不喜欢这样匹配。 在社区中使用 ansible-core 2.15.11。

回答 1 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.