Editor

Fill In a Template

#120 · Parsing · Advanced · 115 XP · about 22 min

Emails that start with "Hi Ada" are made from templates with placeholders. Write render(template, data) that returns template with every placeholder filled in from the dictionary data:

  • {name} is replaced by str(data["name"]).
  • Dots reach into nested dictionaries: {user.city} means data["user"]["city"].
  • {name|fallback} uses the text after the | when the name is missing. A name is missing when a step of its dotted path does not exist, or when a step lands on something that is not a dictionary.
  • A missing name with no fallback leaves the placeholder exactly as it was written, braces and all, so typos are easy to spot.
  • {{ and }} stand for a literal { and }.

A value that exists is always used, even when it is 0, '', False or None.

Examples

render("Hi {name}, you have {count} new messages", {"name": "Ada", "count": 3})
# returns 'Hi Ada, you have 3 new messages'
render("Ship to {user.city|unknown city}", {"user": {"name": "Lin"}})
# returns 'Ship to unknown city'
render("Set {{x}} to {x}, but {y} stays", {"x": 5})
# returns 'Set {x} to 5, but {y} stays'

Constraints

  • template has 0 to 10,000 characters.
  • Placeholders are well formed: a single { is always closed by a } before any other brace, names are made of letters, digits, underscores and dots, and a fallback contains no braces.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.