Search code examples
pythonflaskmarkdownemojiflask-flatpages

Flask Flatpages: how to add (and show) emojis in markdown files?


I have built a static site (Flask app) with Flask-Flatpages (and Flask-Frozen).

Now I want to add emojis inside my markdown text files. How do I do that? This feels like it should be very simple, but couldn't find the answer.

I have e.g. tried bla bla bla :rocket: bla bla to show the well-known rocket emoji, but it shows the text :rocket: instead of the emoji.

I found a really extensive list of emojis here: https://gist.github.com/rxaviers/7360908


Solution

  • With the help of the other answer, I did the follow and succeeded:

    In the app.py file, after the app was created, I added the template_filter:

    app = Flask(__name__)
    app.config.from_object(__name__)
    pages = FlatPages(app)
    freezer = Freezer(app) # Added
    
    app.config['FREEZER_RELATIVE_URLS'] = True
    
    # This part was added:
    import emoji
    @app.template_filter('emojify')
    def emoji_filter(s):
        return emoji.emojize(s)
    

    By doing this I now have a |emojify at my disposal, like |safe etc. inside the template.

    Now inside my page template, I add the newly created filter {{ page.html|emojify|safe }}. (The order matters; I first put it at the end, and then you see the raw html as text.)

    And everything works! Inside one of my markdown files I added a rocket, by simply writing :rocket:, and it was displayed properly.

    More about creating custom filters can be found here: https://flask.palletsprojects.com/en/1.1.x/templating/#registering-filters