当前位置:网站首页>Flask blog practice - archiving and labeling of sidebar articles
Flask blog practice - archiving and labeling of sidebar articles
2022-06-25 10:14:00 【Light programming】
Follow the normal blog site layout , There is usually a sidebar , The common modules in the sidebar are Search for 、 The latest article 、 Article filing 、 Labels etc. ! This tutorial will take you to implement these four modules !
According to the layout of the current project , Our sidebar is only in blog Page display in application , That is, the column list page and details page of the blog are displayed , So this view is through blog Blueprint bound in , Therefore, we only need to focus on this application in the left sidebar !
- Final effect

Realize the article archiving function
stay app/blog/views.py Inject context through the blueprint of the blog , The code is as follows
@bp.context_processor
def inject_archive():
# Article archive date injection context
posts = Post.query.order_by(Post.add_date)
dates = set([post.add_date.strftime("%Y year %m month ") for post in posts])
# label
tags = Tag.query.all()
for tag in tags:
tag.style = ['is-success', 'is-danger', 'is-black', 'is-light', 'is-primary', 'is-link', 'is-info', 'is-warning']
return dict(dates=dates, tags=tags)First of all, we choose to archive by month , That is to put the articles of each month together , Then we must first display the year / month query in the sidebar , The code is as follows :
posts = Post.query.order_by(Post.add_date)
dates = set([post.add_date.strftime("%Y year %m month ") for post in posts])First, query out all the articles and arrange them according to the release time , That is, the newly released articles are at the front , Then extract the month and year of the release date of each article , Use strftime Method to the format we need , And use set Simple de duplication , And return to the context !
Realize the detail view of article archiving
@bp.route('/category/<string:date>')
def archive(date):
# Archive page
import re
# Regular matching year and month
regex = re.compile(r'\d{4}|\d{2}')
dates = regex.findall(date)
from sqlalchemy import extract, and_, or_
page = request.args.get('page', 1, type=int)
# Obtain data according to month and year
archive_posts = Post.query.filter(and_(extract('year', Post.add_date) == int(dates[0]), extract('month', Post.add_date) == int(dates[1])))
# Paging data
pagination = archive_posts.paginate(page, per_page=10, error_out=False)
return render_template('archive.html', post_list=pagination.items, pagination=pagination, date=date)The details view we passed url Pass in the date to access , The year and month are extracted by regular expression , The code is as follows :
import re
# Regular matching year and month
regex = re.compile(r'\d{4}|\d{2}')
dates = regex.findall(date)The following code introduces sqlalchemy Provide extract, and_ Two methods ,extract Used to extract the value of a field ,and_ Realize the relationship between two and , And then according to the regularity, we get Match the month and year to find the articles of that month !
from sqlalchemy import extract, and_, or_
archive_posts = Post.query.filter(and_(extract('year', Post.add_date) == int(dates[0]), extract('month', Post.add_date) == int(dates[1])))Other code has been used many times in previous chapters , You understand it yourself !
Create an archive page template , stay app/blog/templates/ Created in archive.html, The code is as follows :
{% extends 'cate_list.html' %}
{% block title %}{
{ date }} Article archiving for {% endblock title %}
{% block hero %}{% endblock hero %}
{% block breadcrumb %}
<nav class="breadcrumb is-small" aria-label="breadcrumbs">
<ul>
<li><a href="/"> home page </a></li>
<li class="is-active"><a href="#" aria-current="page">{
{ date }} The filing of </a></li>
</ul>
</nav>
{% endblock breadcrumb %}
{% block pagination %}
<nav class="pagination is-small" role="navigation" aria-label="pagination">
{% if pagination.has_prev %}
<a href="{
{ url_for('blog.archive', date=date ) }}?page={
{ pagination.prev_num }}" class="pagination-previous" title="This is the first page">Previous</a>
{% endif %}
{% if pagination.has_next %}
<a href="{
{ url_for('blog.archive', date=date) }}?page={
{ pagination.next_num }}" class="pagination-next">Next page</a>
{% endif %}
<ul class="pagination-list">
{% for page in pagination.iter_pages() %}
{% if page %}
{% if page != pagination.page %}
<li>
<a href="{
{ url_for('blog.archive', date=date) }}?page={
{ page }}" class="pagination-link" aria-label="Page 1" aria-current="page">{
{ page }}</a>
</li>
{% else %}
<li>
<a class="pagination-link is-current" aria-label="Page 1" aria-current="page">{
{ page }}</a>
</li>
{% endif %}
{% else %}
<span class=pagination-ellipsis>…</span>
{% endif %}
{% endfor %}
</ul>
</nav>
{% endblock pagination %}Realize the article tag function
The code in the function is as follows :
# label
tags = Tag.query.all()
for tag in tags:
tag.style = ['is-success', 'is-danger', 'is-black', 'is-light', 'is-primary', 'is-link', 'is-info', 'is-warning']This is very simple. You can directly query all the tags , Here's an extra one style Properties of , Different colors are displayed in coordination with the front end !
Implement tag detail view
@bp.route('/tags/<int:tag_id>')
def tags(tag_id):
# TAB
tag = Tag.query.get(tag_id)
return render_template('tags.html', post_list=tag.post, tag=tag)
Create a tab template , stay app/blog/templates/ Created in tags.html, The code is as follows :
{% extends 'cate_list.html' %}
{% block title %}{
{ tag }} {% endblock title %}
{% block hero %}{% endblock hero %}
{% block breadcrumb %}
<nav class="breadcrumb is-small" aria-label="breadcrumbs">
<ul>
<li><a href="/"> home page </a></li>
<li class="is-active"><a href="#" aria-current="page">{
{ tag }}</a></li>
</ul>
</nav>
{% endblock breadcrumb %}
{% block pagination %}
{% endblock pagination %}Add a sidebar module in the template
stay app/blog/templates/cate_list.html The following code is added to the right block reserved in
<div class="box is-shadowless" style="border:solid 1px #eee ;">
<h1 class="is-size-6 icon-text">
<span class="icon"><i class="mdi mdi-calendar-month-outline"></i></span>
file
</h1>
<div class=" dropdown-divider"></div>
<ul>
{% for date in dates %}
<li class="pl-2"><a href="{
{ url_for('blog.archive', date=date) }}">{
{ date }}</a></li>
<div class="dropdown-divider"></div>
{% endfor %}
</ul>
</div>
<div class="box is-shadowless" style="border:solid 1px #eee ;">
<h1 class="is-size-6 icon-text">
<span class="icon"><i class="mdi mdi-tag-multiple-outline"></i></span>
label
</h1>
<div class=" dropdown-divider"></div>
{% for tag in tags %}
<div class="tags">
<a class="tag {
{ tag.style|random() }}" href="{
{ url_for('blog.tags', tag_id=tag.id) }}">{
{ tag.name }}</a>
</div>
{% endfor %}
</div>Here we have completed two simple modules in the sidebar , In the next chapter, we will implement two modules: search and the latest article !
边栏推荐
- Swift recursively queries the array for the number closest to the specified value
- MySQL create given statement
- Difference between malloc and calloc
- Set the location permission in the shutter to "always allow"
- CYCA 2022少儿形体礼仪初级师资班 深圳总部站圆满结束
- Modbus protocol and serialport port read / write
- Get started quickly with jetpack compose Technology
- BUG-00x bug description + resolve ways
- Mengyou Technology: six elements of tiktok's home page decoration, how to break ten thousand dollars in three days
- Use evo
猜你喜欢

Jetpack compose layout (II) - material components and layout

How to make a self-service order wechat applet? How to do the wechat order applet? visual editing

Vscode attempted to write the procedure to a pipeline that does not exist

【论文阅读|深读】LINE: Large-scale Information Network Embedding

独步武林,架构选型手册(包含 PDF)

Deep understanding of JVM - JVM memory model

How to apply for a widget on wechat how to get a widget on wechat

Yolov5更换上采样方式

【历史上的今天】6 月 24 日:网易成立;首届消费电子展召开;世界上第一次网络直播
![[MySQL learning notes 22] index](/img/08/db7b765f7ddaa5706e3f7d00690d23.png)
[MySQL learning notes 22] index
随机推荐
ShardingSphere-Proxy 4.1 分库分表
在Microsoft Exchange Server 2007中安装SSL证书的教程
Mqtt beginner level chapter
原生小程序开发注意事项总结
JS tool function, self encapsulating a throttling function
How to make small programs on wechat? How to make small programs on wechat
Neat Syntax Design of an ETL Language (Part 2)
How do wechat sell small commodity programs do? How to open wechat apps to sell things?
Requirements and precautions for applying for multi domain SSL certificate
[MySQL learning notes 21] storage engine
Basic usage and principle of schedulemaster distributed task scheduling center
manhattan_ Slam environment configuration
The way that flutter makes the keyboard disappear (forwarding from the dependent window)
manhattan_slam环境配置
【历史上的今天】6 月 24 日:网易成立;首届消费电子展召开;世界上第一次网络直播
tokenizers>=0.11.1,!=0.11.3,<0.13 is required for a normal functioning of this module,
Swift recursively queries the array for the number closest to the specified value
SQL to object thinking vs SQL of object thinking
独步武林,架构选型手册(包含 PDF)
Encoding format for x86