1

I have main index.html file and it contains several links to sub-html files. For example, from index.html if an user clicks an link it directs to sub-page intro.html but seems like render_template only receives one html file. How do I connect multiple html files using render_template?


Files structures: templates/ index.html text.html

I just want to link text.html file from index.html.

In the index.html, I will have a link like the following:

<a href="text.html">Link</a>

Then I want to direct the Link to load the contents of text.html


Second edit

@app.route('/myhtml', methods=['GET'])
def myhtml():
    return render_template('myhtml.html')

I want to to something like this. If I type localhost:8000/myhtml it should link to myhtml.html

  • 1
    ```render_template``` only renders one template at a time and it makes sense. In your template you either want to serve static files or you want to call a view function which in turn will render it's corresponding template. Which one do you want to do? – mehdix Aug 18 '14 at 15:35
  • what do you mean by `view` function? I just want to separate html files and serve them all in one localhost –  Aug 18 '14 at 16:08
  • Put a sample code then I can help you more. By view I mean the function which your request will be routed to. – mehdix Aug 18 '14 at 16:47
  • I added an example. Thanks! –  Aug 18 '14 at 17:05
  • 1
    As I see you only want to serve static html files, for that reason you should use webserver not flask. Anyway flask has some methods for these. Have a look at this answer: http://stackoverflow.com/a/20648053 – mehdix Aug 18 '14 at 17:15
  • I want to to something like this. If I type `localhost:8000/myhtml` it should link to `myhtml.html` –  Aug 18 '14 at 17:20

2 Answers2

0

It's pretty easy-- you just need to capture the file you're requesting from the url, then use that to look up an existing template:

from flask import Flask, render_template, abort
from jinja2 import TemplateNotFound
app = Flask(__name__)

@app.route('/', defaults={'page': 'index'})
@app.route('/<page>')
def html_lookup(page):
    try:
        return render_template('{}.html'.format(page))
    except TemplateNotFound:
        abort(404)

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

If you just try to access 127.0.0.1:5000 it'll default the page variable to index and therefore will try and render_template('index.html') whereas if you try 127.0.0.1:5000/mypage it will instead search for mypage.html.

If it fails, it'll abort with a 404 not found error.

This example, totally cribbed from the simple blueprint example in the Flask documentation.

Doobeh
  • 9,280
  • 39
  • 32
0

In your index.html file use this:

<a href="/about">Link</a>

And then you need a corresponding route that looks like this:

@app.route('/about')
def about_page():

    # Do something else here

    return render_template('text.html')

if __name__ == '__main__':
    app.run()
Raj
  • 3,791
  • 5
  • 43
  • 56