G
G
gosha_tst2018-07-10 21:14:53
Flask
gosha_tst, 2018-07-10 21:14:53

How to organize adding new html elements with database extension?

I'm making a blog in flask. The problem is in creating a news feed: a new "article" is added to the database => a new div is created with its own style, text inside and a link to which it leads when clicked. Each column of the database stores the title of the "article", the link generated to it, the date of creation and the text itself. How can I organize the automatic addition of html blocks to the news feed? Through JavaScript? If so, how then to call a JavaScript function through Flask?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2018-07-11
@gosha_tst

Off cos, guys here are stingy with words, but I'm kind, I'll tell you. :-D
There is a templating engine in the flask, usually jinja.pocoo.org
There are cycles, they look something like this

{% extends "layout.html" %}
{% block news %}
  <div class="news--block">
  {% for item in news %}
    <div class="news--item">
    <h1>{{ item.header }}</h1>
    {{ item.body }}
   </div>
  {% endfor %}
  </ul>
{% endblock %}

So from this example: news is an array of "news" objects that we iterate through the loop and output to the news block.
In the method, we do something like this:
from flask import render_template

@app.route('/')
def hello(name=None):
    news = [{"header":"Fake news: Trump died", "body":"Sorry, world."}, {"header":"Fake news: Trump now alive", "body":"Sorry, world again."}]
    return render_template('main.html', news=news)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question