jinja2模板未找到,内部服务器错误 [英] jinja2 template not found and internal server error

查看:497
本文介绍了jinja2模板未找到,内部服务器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python代码:

  from flask import Flask,render_template 

app = Flask(__ name__)

@ app.route(/)

def hello():

return render_template .html')

if __name__ ==__main__:
app.run()



Html文件:

 <!DOCTYPE html> 
< html lang =en>
< head>
< meta charset =UTF-8>
< title>标题< / title>
< / head>
< body>
< h1>我的名字是pk< / h1>
< / body>
< / html>

另外如何在pycharm社区版本中启用jinja2。我直接在同一个项目中创建html文件和.py文件

解决方案

默认情况下,Flask在 templates 文件夹。


$ b


http://flask.pocoo.org/docs/0.10/api/

template_folder - 包含应该使用
的模板的文件夹被应用程序使用。默认是应用程序的根目录
路径中的templates文件夹。

所以你有一些选择,


  1. 重命名模板模板

  2. 提供一个 template_folder param让您的模板应用程序:

      app = Flask(__ name__,template_folder ='template')




  3. Flask期望模板目录与创建它的模块位于相同的文件夹中;
    你需要告诉Flask看看别的地方:

    $ $ $ $ $ c $ app $ Flask(__ name__,template_folder ='。 ./pages/templates')

    当路径相对于当前模块路径被解析时,

    你不能拥有每个模块的模板目录,而不是没有使用蓝图。一个常见的模式是使用模板文件夹的子目录来分割你的模板。你可以使用 templates / pages / index.html ,加载 render_template('pages / index.html')等等。

    Python code:

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route("/")
    
    def hello():
    
        return render_template('testing.html')
    
    if __name__ == "__main__":
        app.run()
    

    Html file:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h1>My name is pk</h1>
    </body>
    </html>
    

    Also how to enable jinja2 in pycharm community version. I am directly creating html file and .py file in the same project

    解决方案

    By default, Flask looks in the templates folder in the root level of your app.

    http://flask.pocoo.org/docs/0.10/api/

    template_folder – the folder that contains the templates that should be used by the application. Defaults to 'templates' folder in the root path of the application.

    So you have some options,

    1. rename template to templates
    2. supply a template_folder param to have your template folder recognised by the flask app:

      app = Flask(__name__, template_folder='template')
      

    Flask expects the templates directory to be in the same folder as the module in which it is created; You'll need to tell Flask to look elsewhere instead:

    app = Flask(__name__, template_folder='../pages/templates')
    

    This works as the path is resolved relative to the current module path.

    You cannot have per-module template directories, not without using blueprints. A common pattern is to use subdirectories of the templates folder instead to partition your templates. You'd use templates/pages/index.html, loaded with render_template('pages/index.html'), etc.

    这篇关于jinja2模板未找到,内部服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆