新人写 django 自定义模板标签出问题了,求助

2019-04-16 23:38:56 +08:00
 vectorChange

我检查过自己的 template tags 了,并没有漏过了步骤 {% load blog_tags %}

blog_tags.py

register = template.Library()
@register.simple_tag

html 模板上并没有任何的语法问题,上网百度搜索这个错误,根本找不到解决办法

html 模板上的一些片段

50 {% archives as date_list %} 
51 <div class="list-group"> 
52 <a href="#" class="list-group-item list-group-item-action active"> 
53 归档 
54 </a> {% for date in date_list %} 
55 <a href="#" class="list-group-item list-group-item-action"> 
56 <i class="fa fa-calendar-o"></i><span> {{ date.year }} 年 {{ date.month }} 月</span> 
57 </a> 
58 {% empty %} 暂无归档! {% endfor %} 
59 </div>

返回的是这个错误


django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 50: 'archives', expected 'endblock'. Did you forget to register or load this tag?
3860 次点击
所在节点    Django
6 条回复
GTim
2019-04-17 07:20:58 +08:00
因为 {% archive as %} 并不是合法的标签语法
vectorChange
2019-04-17 16:12:45 +08:00
@GTim 那么请问,怎么样才是合法的呢,我之前看的教程里面这么写是没有问题的,而且我自己下载过也是能运行的,是 django 版本的问题么? [教程里面的是 1.10 而我现在用的是 2.10]
vectorChange
2019-04-17 16:19:41 +08:00
@GTim 而且关键是官网介绍例子里面也是有这种语法的

https://docs.djangoproject.com/zh-hans/2.1/howto/custom-template-tags/#writing-custom-template-tags

```
It's possible to store the tag results in a template variable rather than directly outputting it. This is done by using the as argument followed by the variable name. Doing so enables you to output the content yourself where you see fit:
```
```
{% current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>
```
GTim
2019-04-17 18:09:12 +08:00
你把 blog_tags.py 全部贴出来看看
vectorChange
2019-04-20 10:47:42 +08:00
@GTim 感谢老铁对我的问题给予了回应,问题我自己解决了

是因为一个奇怪的问题引起的

之前弄了一个

类似

----base.html
------index.html

的目录架构
在 index.html 里面是
{% extends 'base.html' %}引用了 base 文件的

而我的{% load blog_tags %}是写在 base.html 文件里面的

我自己尝试了一下,把{% load blog_tags %}移动到 index.html 文件里面,发现问题解决了



明明之前已经引用了 base.html,却没有把{% load blog_tags %}这个也引用过来,真不懂这个模板模块是不是出毛病了
jinhb
2020-02-09 17:55:12 +08:00
老哥求完整的网址!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/555847

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX