How to flashing a message with link using Flask flash?

前端 未结 4 1411
清歌不尽
清歌不尽 2021-02-19 04:34

I\'m creating a web app using Flask to deal with GoogleOpenID, these codes are almost finished, except the flashing message contains a link:

@oid.after_login
def         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 05:40

    I am not sure if it is correct, but the way I solved this was by declaring another variable in the function that was a string of HTML and then passing it through a render_template() function.

    And in the template passed it through the safe filter.

    For example, (roughly based on) the code you have provided:

    @oid.after_login
    def create_or_login(resp):
        user = db_session.query(User).filter_by(email=resp.email).first()
        if user is not None:
            flash('Successfully signed in', 'success')
        else:
            user = User(nickname=resp.fullname, source=GOOGLE, email=resp.email)
            db_session.add(user)
            db_session.commit()
            flash(flashing_message, 'success')
            link = "Link" ## ADDED HTML WITH LINK ##
        g.user = user
        session['nickname'] = user.nickname
        return render_template('some_layout.html',
                               link=link  ## PASS THE LINK TO THE TEMPLATE ##
        )
    

    Then in the template I added an extra if statement inside the get_flashed_messages() if:

    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
    
        ... Code that was already here ...
    
        {% if link %}        ## PASSED THE LINK TO THE TEMPLATE HERE ##
          {{ link | safe }}
        {% endif %}
    
        {% endif %}
    {% endwith %}
    

提交回复
热议问题