加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Django’include’语句中的多行字符串

发布时间:2020-12-20 13:40:23 所属栏目:Python 来源:网络整理
导读:我正试图用我的Django模板干,并有一些代码,我与CSS混合使用简单的悬停弹出窗口.我想重用代码,但我的弹出窗口的内容将是 HTML,可能跨越多行.是否可以将多行字符串填充到模板变量中? 我尝试用block和block.super做一些时髦的东西,但这似乎只在扩展时工作(不包
我正试图用我的Django模板干,并有一些代码,我与CSS混合使用简单的悬停弹出窗口.我想重用代码,但我的弹出窗口的内容将是 HTML,可能跨越多行.是否可以将多行字符串填充到模板变量中?

我尝试用block和block.super做一些时髦的东西,但这似乎只在扩展时工作(不包括)

这是我想做的一个例子.可能吗?

的index.html

<body>
 <h2>My Popup</h2>
 {% include "snippets/popup.html" with class="p" spantext="Hover me" popupdiv="""
  <h2>This is a popup!</h2>
     <ul>
          <li>Something</li>
          <li>Something else</li>
     </ul>
 """
%}
 </body>

片段/ popup.html

<div class="{{ class }}">
     <span class='pointer'>{{ spantext }}</span>
     <div class="popup">
         {{ popupdiv }}
     </div>
 </div>

我知道在Django中不可能有多行模板标签,但除了将我所有的div html压缩到一行之外,有什么方法可以解决这个问题吗?

干杯

解决方法

结果是“解析直到另一个模板标签”就是我所追求的. http://www.djangobook.com/en/2.0/chapter09.html

这是我的代码:

tags.py(在templatetags文件夹中)

from django import template
from django.template.loader import get_template
from django.template.base import Node,TemplateSyntaxError

register = template.Library()

class PopupNode(Node):
    def __init__(self,nodelist,class_name,spantext):
        self.nodelist = nodelist
        self.class_name = class_name
        self.spantext = spantext

    def render(self,context):
        popup_html = get_template("ordersystem/snippets/popup.html")
        context.update({
            'class' : self.class_name,'spantext' : self.spantext,'popupdiv' : self.nodelist.render(context)
        })
        return popup_html.render(context)

@register.tag('popup')
def show_popup(parser,token):
    nodelist = parser.parse(('endpopup',))
    tokens = token.split_contents()
    if len(tokens) != 4:
        raise TemplateSyntaxError("show_popup is in the format 'popup with class=X spantext=Y")
    try:
        context_extras = [t.split("=")[1].strip('"') for t in tokens[2:]]
    except IndexError:
        raise TemplateSyntaxError("show_popup is in the format 'popup with class=X spantext=Y")
    parser.delete_first_token()
    return PopupNode(nodelist,*context_extras)

然后在我的html文件中,我可以这样做:

{% popup with class_name=management spantext=Manage %}
<h2>This is a popup!</h2>
     <ul>
          <li>Something</li>
          <li>Something else</li>
     </ul>
{% endpoup %}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读