2

I am fairly new to flask and am trying to create a personal website as an exercise. I'm looking to build a project page, I wanted to ask the following questions regarding file and project url path:

  1. I am trying to put all my project pages in the /projects folder. How do I render_template from a different folder so that proj1() function is pulling from /projects/proj1.html instead of /tempates/.proj1.html? Is there a better way of specifying a different folder location?
  2. In app.py, I have @app.route("/projects/project1") hard-coded in for proj1.html. What is a better way to change this so that it can create a path for other projects like proj2.html and proj3.html? I believe I may need to write something like @app.route("/projects/<project>") and pass in the project name somehow?

Here is the folder structure:

/project
    app.py
    /templates
        home.html
        about.html
        layout.html
        proj1.html
        projects.html
    /projects
        proj1.html
        proj2.html
        proj3.html

My app.py looks like this:

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html')

@app.route("/projects/")
def projects():
    return render_template('projects.html', title='Projects')

@app.route("/projects/project1")
def proj1():
    return render_template('proj1.html')

if __name__ == '__main__':
    app.run(debug=True)

Inside projects.html I have the following:

<h2><a href="project1">Project Link</a></h2>

Thank you! There's still a lot more work to be done, but I would set up the project page for now.

bltSandwich21
  • 432
  • 3
  • 10

2 Answers2

1

This seems like better organization:

/project
    app.py
    /templates
        home.html
        about.html
        layout.html
        proj1.html
        projects.html
        /projects
            proj1.html
            proj2.html
            proj3.html
    

Then, use return render_template('projects/proj1.html')

That way all templates are in the templates directory, which is the default for Flask. If you insist on using a separate dir, check the update on this answer: How to reference a html template from a different directory in python flask

GAEfan
  • 11,244
  • 2
  • 17
  • 33
0

I also found this interesting answer: How to dynamically select template directory to be used in flask?

Check the answer form Ignas Butėnas is pretty interesting and he refers to the jinja2.FileSystemLoader class, also explained in greater details here: Jinja API

Also in the Flask Api Docs Template folder it explains the following:

  • 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.
Federico Baù
  • 6,013
  • 5
  • 30
  • 38