V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
vectorChange
V2EX  ›  Django

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

  •  
  •   vectorChange · Apr 16, 2019 · 4839 views
    This topic created in 2568 days ago, the information mentioned may be changed or developed.

    我检查过自己的 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 replies    2020-02-09 17:55:12 +08:00
    yemoluo
        1
    yemoluo  
       Apr 17, 2019 via iPhone
    因为 {% archive as %} 并不是合法的标签语法
    vectorChange
        2
    vectorChange  
    OP
       Apr 17, 2019
    @GTim 那么请问,怎么样才是合法的呢,我之前看的教程里面这么写是没有问题的,而且我自己下载过也是能运行的,是 django 版本的问题么? [教程里面的是 1.10 而我现在用的是 2.10]
    vectorChange
        3
    vectorChange  
    OP
       Apr 17, 2019
    @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>
    ```
    yemoluo
        4
    yemoluo  
       Apr 17, 2019   ❤️ 1
    你把 blog_tags.py 全部贴出来看看
    vectorChange
        5
    vectorChange  
    OP
       Apr 20, 2019
    @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  
       Feb 9, 2020
    老哥求完整的网址!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   939 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 21:35 · PVG 05:35 · LAX 14:35 · JFK 17:35
    ♥ Do have faith in what you're doing.