个人名片
作者简介:java领域优质创作者
个人主页:码农阿豪
工作室:新空间代码工作室(提供各种软件服务)
个人邮箱:[[email protected]]
个人微信:15279484656
个人导航网站:www.forff.top
座右铭:总有人要赢。为什么不能是我呢?
码农阿豪系列专栏导航
面试专栏:收集了java相关高频面试题,面试实战总结️
Spring5系列专栏:整理了Spring5重要知识点与实战演练,有案例可直接使用
Redis专栏:Redis从零到一学习分享,经验总结,案例实战
全栈系列专栏:海纳百川有容乃大,可能你想要的东西里面都有
{% if user.age < 18 %}
<p>未成年用户p>
{% elif user.age > 60 %}
<p>老年用户p>
{% else %}
<p>成年用户p>
{% endif %}
<table>
<thead>
<tr>
<th>序号th>
<th>标题th>
<th>内容th>
tr>
thead>
<tbody>
{% for post in posts %}
<tr class="{{ loop.cycle('odd', 'even') }}">
<td>{{ loop.index }}td>
<td>{{ post.title }}td>
<td>{{ post.content }}td>
tr>
{% else %}
<tr>
<td colspan="3">暂无文章td>
tr>
{% endfor %}
tbody>
table>
循环变量说明:
loop.index
: 当前迭代次数(从1开始)loop.index0
: 当前迭代次数(从0开始)loop.revindex
: 反向迭代次数loop.first
: 是否第一次迭代loop.last
: 是否最后一次迭代loop.length
: 序列长度定义宏:
{% macro render_comment(comment) %}
<div class="comment">
<p>{{ comment.author }} 说:p>
<blockquote>{{ comment.content }}blockquote>
div>
{% endmacro %}
使用宏:
{{ render_comment(comment) }}
{% from 'macros.html' import render_comment %}
DOCTYPE html>
<html>
<head>
<title>{% block title %}默认标题{% endblock %}title>
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
{% endblock %}
head>
<body>
<div class="container">
{% block content %}
<h1>默认内容h1>
{% endblock %}
div>
{% block footer %}
<footer>
<p>© 2023 My Appp>
footer>
{% endblock %}
body>
html>
{% extends "base.html" %}
{% block title %}用户主页 - {{ super() }}{% endblock %}
{% block head %}
{{ super() }}
<style>
.profile { color: blue; }
style>
{% endblock %}
{% block content %}
<div class="profile">
<h1>{{ user.username }}的个人资料h1>
<p>年龄: {{ user.age }}p>
div>
{% endblock %}
{% block footer %}
<footer>
<p>© 2023 用户中心p>
footer>
{% endblock %}
{% include 'header.html' %}
{% include 'user_card.html' with user=current_user %}
{% include 'sidebar.html' ignore missing %}
标准项目结构:
myapp/
├── app.py
├── static/
│ ├── css/
│ ├── js/
│ └── images/
└── templates/
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="{{ url_for('static', filename='js/main.js') }}">script>
<img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css', v=1.0) }}">
在配置中添加版本号:
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600 # 1小时缓存
app.config['STATIC_VERSION'] = '1.0.0'
模板中使用:
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}?v={{ config.STATIC_VERSION }}">
{% if config.CDN_ENABLED %}
<script src="https://cdn.example.com/jquery/3.6.0.min.js">script>
{% else %}
<script src="{{ url_for('static', filename='js/jquery.min.js') }}">script>
{% endif %}
在这两篇教程中,我们全面学习了Flask模板系统的各个方面:
这些知识构成了Flask前端开发的基础,掌握它们后,你已经能够构建结构清晰、易于维护的Web应用界面。在接下来的专栏中,我们将深入探讨Flask的表单处理、数据库集成和用户认证等高级主题。