Skip to content

demo posts

Manish Sah edited this page Sep 19, 2020 · 1 revision

adding demo posts

so far we have added navigation bar, but the home page is still empty. We will be adding some demo posts (which in future will be replaced by posts added by users)

lets add some posts in our routes.py and update home route as follows

blog/routes.py

@app.route("/")
def home():
    posts = [
    {
        'author': 'User first',
        'title': 'blog post one',
        'content': 'These are the contents for the first post',
        'date_posted': '2020-09-19'
    },
    {
        'author': 'User Second',
        'title': 'blog post two',
        'content': 'second post content',
        'date_posted': '2020-09-20'
    }
]
    return render_template('home.html', posts=posts)

Now, we will render these posts in home.html by adding these codes inside content block

 {% for post in posts %}
        <h3>{{ post.author }}</h3>
        <h2>{{ post.title }}</h2>
        <p>{{ post.content }}</p>
        <br>
    {% endfor %}

now our home.html will be like this:

templates/home.html

{% extends 'layout.html' %}
{% block content %}
    {% for post in posts %}
        <h3>{{ post.author }}</h3>
        <h2>{{ post.title }}</h2>
        <p>{{ post.content }}</p>
        <br>
    {% endfor %}
{% endblock content %}

We can access the dictionary keys using dot(".") operator

Now we have some content for our home page. Lets improve the style for our posts. Replace everything inside for loop with these codes

<article class="media content-section">
    <div class="media-body">
        <div class="article-metadata">
            <a class="mr-2" href="#">{{ post.author }}</a>
            <small class="text-muted">{{ post.date_posted }}</small>
        </div>
        <h2><a class="article-title" href="#">{{ post.title }}</a></h2>
        <p class="article-content">{{ post.content }}</p>
    </div>
</article>

home.html will now look like this:

{% extends 'layout.html' %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
    <div class="media-body">
        <div class="article-metadata">
            <a class="mr-2" href="#">{{ post.author }}</a>
            <small class="text-muted">{{ post.date_posted }}</small>
        </div>
        <h2><a class="article-title" href="#">{{ post.title }}</a></h2>
        <p class="article-content">{{ post.content }}</p>
    </div>
</article>
{% endfor %}
{% endblock content %}

Implementation can be found over this commit

Clone this wiki locally