jinja2 相关问题

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

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

Jinja2(flask):如何将块传递给宏?

我正在实现一个Python Flask Web应用程序,我正在尝试编写一个宏,我想向其中传递三个HTML代码块,但无法运行它。 我找到了一个使用 jinja 的简单示例

回答 1 投票 0

bootstrapTable加载功能不生成复选框

我使用以下代码创建了一个 html 表格: 我使用以下代码创建了一个 html 表格: <table id="vendor-table" data-toggle="table" data-sort-class="table-active" data-sortable="true" data-search="true",data-virtual-scroll="false"> <thead> <tr> <th></th> <th data-field="brand" data-sortable="true">Brand </th> <th data-field="client" data-sortable="true">Client</th> <th data-field="spid" data-sortable="true">Selling Partner ID</th> <th data-field="acct" data-sortable="true">Account Type</th> <th data-field="cc" data-sortable="true">Country Code</th> </tr> </thead> <tbody></tbody> </table> 我创建了一个函数来填充表格。下面是函数: function updateVendorTable(filteredVendorAccts) { var table = $('#vendor-table'); // Map the data to include the checkbox column before the id column var mappedData = filteredVendorAccts.map(function (account) { return { '':'<label class="checkbox"><input type="checkbox" name="vendor-ids" value="' + account.id + '" /></label>', brand: account.brand, client: account.client, spid: account.sp_id, acct: account.account_type, cc: account.country_code }; }); // Update the table data using the load method table.bootstrapTable('load', mappedData); } 我希望 html 包含函数返回的第一个值的复选框,即“:”,但复选框列填充有 -。下面是截图: 我已确保返回“”列的值。下面是一个例子: { "": "<label class=\"checkbox\"><input type=\"checkbox\" name=\"vendor-ids\" value=\"15324\" /></label>", "brand": "Edge", "client": "GSK_DE", "spid": "amzn1.vg.5666682", "acct": "vendor", "cc": "DE", "id": 15324 } 我错过了什么吗?以下是预期输出: 任何帮助将不胜感激。 文档就绪:使用 $(document).ready() 确保代码在文档完全加载后运行。 $(document).ready(function () { let data = [ { "": '<label class="checkbox"><input type="checkbox" name="vendor-ids" value="15324" /></label>', brand: "Edge", client: "GSK_DE", spid: "amzn1.vg.5666682", acct: "vendor", cc: "DE",`enter code here` id: 15324, }, ]; // Initialize table with data updateVendorTable(data); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.21.1/bootstrap-table.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.21.1/bootstrap-table.min.css" rel="stylesheet" /> <title>Bootstrap Table Example</title> </head> <body> <div class="container mt-5"> <table id="vendor-table" data-toggle="table" data-sort-class="table-active" data-sortable="true" data-search="true" ,data-virtual-scroll="false"> <thead> <tr> <th></th> <th data-field="brand" data-sortable="true">Brand</th> <th data-field="client" data-sortable="true">Client</th> <th data-field="spid" data-sortable="true">Selling Partner ID</th> <th data-field="acct" data-sortable="true">Account Type</th> <th data-field="cc" data-sortable="true">Country Code</th> </tr> </thead> <tbody></tbody> </table> </div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.21.1/bootstrap-table.min.js"></script> <script> $(document).ready(function () { let data = [ { "": '<label class="checkbox"><input type="checkbox" name="vendor-ids" value="15324" /></label>', brand: "Edge", client: "GSK_DE", spid: "amzn1.vg.5666682", acct: "vendor", cc: "DE", id: 15324, }, ]; // Initialize table with data updateVendorTable(data); }); function updateVendorTable(filteredVendorAccts) { var table = $("#vendor-table"); // Map the data to include the checkbox column before the id column var mappedData = filteredVendorAccts.map(function (account) { return { "": `<label class="checkbox"><input type="checkbox" name="vendor-ids" value="${account.id}" /></label>`, brand: account.brand, client: account.client, spid: account.spid, acct: account.acct, cc: account.cc, }; }); table.bootstrapTable("load", mappedData); } </script> </body> </html>

回答 1 投票 0

创建系统接口名称及其 MAC 地址的列表

我正在尝试从 Debian 11 服务器创建接口名称及其 mac 地址列表,最初,我试图仅按顺序获取 mac 地址,但现在我意识到我需要一个列表...

回答 2 投票 0

如何在烧瓶中创建链式选择字段而不刷新页面?

我目前正在使用 wtf 制作地址表单,其中包含国家、州、城市等。数据库全部用FK设置。 国家/地区类(db.Model): __tablename__ = '国家' id = 数据库。

回答 2 投票 0

从主机变量(非静态清单)创建 IP 地址及其匹配网络掩码的列表

运行剧本时,很容易使用 ansible_all_ipv4_addresses 获取所有 IP 地址,稍后在主机变量中也很容易找到分配给每个接口的网络掩码,例如: ...

回答 1 投票 0

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.