V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
vectorChange
V2EX  ›  Django

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

  •  
  •   vectorChange · 2019-04-16 23:38:56 +08:00 · 3820 次点击
    这是一个创建于 1808 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我检查过自己的 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>
    

    avatar

    返回的是这个错误

    
    django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 50: 'archives', expected 'endblock'. Did you forget to register or load this tag?
    
    6 条回复    2020-02-09 17:55:12 +08:00
    GTim
        1
    GTim  
       2019-04-17 07:20:58 +08:00 via iPhone
    因为 {% archive as %} 并不是合法的标签语法
    vectorChange
        2
    vectorChange  
    OP
       2019-04-17 16:12:45 +08:00
    @GTim 那么请问,怎么样才是合法的呢,我之前看的教程里面这么写是没有问题的,而且我自己下载过也是能运行的,是 django 版本的问题么? [教程里面的是 1.10 而我现在用的是 2.10]
    vectorChange
        3
    vectorChange  
    OP
       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
        4
    GTim  
       2019-04-17 18:09:12 +08:00   ❤️ 1
    你把 blog_tags.py 全部贴出来看看
    vectorChange
        5
    vectorChange  
    OP
       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
        6
    jinhb  
       2020-02-09 17:55:12 +08:00
    老哥求完整的网址!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1553 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:12 · PVG 01:12 · LAX 10:12 · JFK 13:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.