Insert static files literally into Jinja templates without parsing them

前端 未结 5 1734
逝去的感伤
逝去的感伤 2020-12-15 07:09

I\'m trying to insert file into a page using Jinja 2.6 using the include tag. This worked fine until I started using characters in the file that are reminiscent

5条回答
  •  一向
    一向 (楼主)
    2020-12-15 07:17

    As an update to @Alex's answer, you can use Jinja's @contextfunction decorator to remove some of the reliance on global variables. The updated code would look like:

    import jinja2                                                                                                                                                                                                  
    
    @jinja.contextfunction                                                                                                                                                                                         
    def include_file(ctx, name):                                                                                                                                                                                   
        env = ctx.environment                                                                                                                                                                                      
        return jinja2.Markup(env.loader.get_source(env, name)[0])                                                                                                                                                  
    
    
    def main():                                                                                                                                                                                                    
        loader = jinja2.PackageLoader(__name__, 'templates')                                                                                                                                                       
        env = jinja2.Environment(loader=loader)                                                                                                                                                                    
        env.globals['include_file'] = include_file                                                                                                                                                                 
    
        env.get_template('page.html').render()                                                                                                                                                                     
    
    
    if __name__ == '__main__':                                                                                                                                                                                     
        print main()
    

    And just as before, call it from your template like:

    {{ include_file('file.txt') }}
    

提交回复
热议问题