包括css和/或脚本从模板标签

Include css and/or script from template tag

本文关键字:标签 脚本 css 包括      更新时间:2023-09-26

我有一个Django应用程序,使用模板标签来处理wordpress样式的短代码。我的代码是基于https://github.com/emilbjorklund/django-template-shortcodes/blob/master/shortcodes,但我已经添加了我自己的解析器。短代码基本上是一个图像相册,例如[album view=slideshow id=1],其中视图可以是幻灯片(Bootstrap Carousel)或画廊(Lightbox)。我的解析器看起来像:

def parse(tag_atts, tag_contents=None):
    #Check our id is a digit.
    tag_atts['content'] = "Album Short Tag Error"
    if tag_atts['id'].isdigit:
        #try:
        # Get the data from the album
        album = Album.objects.get(pk = tag_atts['id'] )#.select_related()
        images = Image.objects.filter(album__id=album.id)
        if tag_atts['view']=='gallery':
            return makeGallery(album,images,tag_atts)
        elif tag_atts['view']=='slideshow':
            return makeSlideshow(album,images,tag_atts)
        else:
            context = Context(tag_atts)
            t = Template("""{{ content }}""")
            return t.render(context)

makeGallery和makeSlideshow函数只是处理短代码及其属性,返回一个带有所有必需HTML的渲染模板,就像给定的else子句一样,但更复杂(参见github解析器示例了解想法)。

一切都很好,但我需要包括一个自定义的css文件和javascript文件的实例,它的画廊视图已被请求的灯箱。目前,这是包含在使用自定义块的主页模板文件中,但这意味着无论短代码是否存在或已请求的图库,它始终存在。

告诉Django只在需要的时候从模板标签中包含这些额外的文件的合适方法是什么?

我讨厌添加一个额外的'checker'标签来解析customcss header块中的页面内容,以查看是否包含它,并再次为customscript块中的页脚。

我期待听到更多有经验的django用户的声音。

克里斯

使用模板继承,根据django文档。请注意,这些都是非常通用的例子,它应该足以让你通过。请务必查看我上面链接的文档。

<标题> base_page.html h1> gallery_template.html h1> slideshow_template.html h1> 的视图函数
#camelcase is fine, consistency is important though. 
def make_gallery(album,images,tag_atts) 
    #do things here
    return render_to_response('path/to/gallery_template.html')
def make_slideshow(album,images,tag_atts)
    #do things here
    return render_to_response('path/to/slideshow_template.html')
相关文章: