[Python #12] [Django #5] Template tags, filters 使用记

pixabay

把文章列表投到网页时遇到了一个问题,get_blog()函数返回的参数里没有缩略图参数导致列表不显示缩略图。
再研究下函数把👇

[{'blog': 'steem.scot',
  'comment': {'active_votes': [],
              'author': 'steem.scot',
              'author_reputation': 0,
              'beneficiaries': [],
              'body': '|table|테이블|表格|\n'
                      '|---|----|---|\n'
                      '|table cell|테이블 셀|表格内容|\n'
                      'pixabay\n'
                      'https://cdn.pixabay.com/photo/2015/06/02/12/59/narrative-794978_1280.jpg\n'
                      '\n'
                      'CONTENT, content 내용입니다. 本文测试。\n'
                      '\n'
                      '\n'
                      '![stained-glass-1181864_1280.jpg](https://cdn.steemitimages.com/DQmSvFnsanUa6uxLS3qzTkiTBj7HK5oYs3hGhZySGCW9iUS/stained-glass-1181864_1280.jpg)\n'
                      '\n'
                      '\n'
                      '> 인용문',
              'body_length': 319,
              'cashout_time': '2020-08-30T05:46:54',
              'category': 'qa',
              'children': 0,
              'created': '2020-08-23T05:46:54',
              'curator_payout_value': '0.000 SBD',
              'depth': 0,
              'json_metadata': '{"tags":["qa","test1","korea","china"],"image":["https:\\/\\/cdn.pixabay.com\\/photo\\/2015\\/06\\/02\\/12\\/59\\/narrative-794978_1280.jpg","https:\\/\\/cdn.steemitimages.com\\/DQmSvFnsanUa6uxLS3qzTkiTBj7HK5oYs3hGhZySGCW9iUS\\/stained-glass-1181864_1280.jpg"],"app":"steemit\\/0.2","format":"markdown"}',
              'last_payout': '1969-12-31T23:59:59',
              'last_update': '2020-08-23T05:46:54',
              'max_accepted_payout': '1000000.000 SBD',
              'net_rshares': 0,
              'parent_author': '',
              'parent_permlink': 'qa',
              'pending_payout_value': '0.000 SBD',
              'percent_steem_dollars': 10000,
              'permlink': 'test-1',
              'post_id': 87205021,
              'promoted': '0.000 SBD',
              'replies': [],
              'root_title': '[Test #1] 测试 한글',
              'title': '[Test #1] 测试 한글',
              'total_payout_value': '0.000 SBD',
              'url': '/qa/@steem.scot/test-1'},
  'entry_id': 0,
  'reblogged_on': '1970-01-01T00:00:00'}]

有两个方法可以解决缩略图问题。一个是通过body 值获取图片URL,再一个是通过'json_metadata'值获取image值。第一个比较麻烦,应该用正规表达式来处理,但我不是开发者啊,不太懂这玩意。第二个方法应该轻松许多,因为'json_metadata'值为 json 格式,很容易抽取内部 image值。但看'json_metadata'值虽然是json但类型是String,我应该先把这String转换成dict。

那,写在哪里好呢?与get_blog()一起写在view.py?还是写在html文件?
第一个觉得蛮复杂,获取数据后写一个循环抽出image值并且另存到别的地方,最后再次获取。很麻烦。最好少用循环吧,毕竟在 html 文件还会有一个循环。利用这个循环抽取image觉得胜于第一个方法。我猜django应该会有方法,于是询问谷歌,果真~~~

Template filters 可以解决这个问题。
若想用Template filters,必须在app目录下创建名为 templatetags 文件夹,并且在这文件夹下新建一个文件为 init.py。还需要创建一个管理自定义函数的文件,我新建的是 str_to_dict 。 👇

from django import template
import json

register = template.Library()


@register.filter
def str_to_dict(string):
    return json.loads(string)

之后在html文件,用 {% load post_extras %}来倒入模板,并且在适当的为止调用 str_to_dict 函数即可。
语法很陌生,{% with post.comment.json_metadata|str_to_dict as extras %}。|左侧为参数, 右侧是调用 str_to_dict ,并给变量 extras负值。其后往 img 标签的 src 属性负值 image list的第一个值。src="{{ extras.image.0 }}"

运行后大部分图片正常,但用appics写的文章不显示图片,原来appics上传的数据里没有json_metadata值,无所谓,反正appics都不用了。👇

.
.
.
.
[Cookie 😅]
Python 3.7.4
Django 2.2.4
steem-python 1.0.1
goorm IDE 1.3

参考文章:
https://wayhome25.github.io/django/2017/06/22/custom-template-filter/

https://www.pymoon.com/entry/djang-%ED%85%9C%ED%94%8C%EB%A6%BF%EC%97%90%EC%84%9C-custom-tag-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

https://amoreopensource.wordpress.com/2019/04/23/access-jsonfield-in-django-templates-like-a-dictionary/

Sort:  

@june0620, Application Development Languages looks like other worldly language specially for those who knows nothing about the Application Development or who is not a developer. Stay blessed.

Thank you for your comments,@chireerocks
I'm learning development languages one by one. (I'm not a developer)
Stay blessed.😃

Welcome and thank you. 🙂

@tipu curate

😁 萍萍好,多谢🙏