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

Viewed 498

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

2 Answers

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

Emojis have nothing to do with Markdown, and as far as I know they don't have anything to do with Flask-FlatPages or Frozen-Flask. To render them, you'll need to do a bit of extra work.

One option is to install something like emoji and then use it, e.g. (example from the README):

>>> import emoji
>>> print(emoji.emojize('Python is :thumbs_up:'))
Python is 

I suggest writing (or finding) a filter for whatever templating language you are using so you can do something like

{{ text | emojify }}
Related