PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Integrating Markdown with Symfony

Note: This article was originally published at Planet PHP on 26 April 2011.
Planet PHP

Context

I needed to create a number of static help pages in three languages in a Symfony 1.4 application.AUsing the XLIFF translation files seemed absurd, since I knew that I will include a lot of html. As you know, XLIFF translation files are XML, and so any html needs to be converted to entities, which makes maintenance a pain. Also, loading the entire manual's XLIFF when requesting a single page is not optimal.AAnd so, I decided to create partials using the following structure: _docs/{lang}/{title}.php. This method would organize my pages nicely and will only load what is needed.

Then, I remembered that we were planning to hire a technical writer for the rest of the manual. I wanted to make his life as easy as possible and the source files easy to read for everyone. I went that far; I might as well write the manual using Markdown. Because SymfonyAcan cache static pages, Markdown will only parse each page once. I did not have to worry about performance! Here is how to quickly add Markdown to your Symfony 1.4 application.

Solution

  1. Download the paser
  2. Copy the PHP file to your lib/helper or apps/{application}/lib/helper directory
  3. Rename the file to MarkdownHelper.php
  4. In your controller, load the Partial helper: $this-getContext()-getConfiguration()-loadHelpers(array(aPartial'));
  5. Load your partial: $this-content = get_partial(a{module}/{partial}');
  6. In your template, load the Markdown helper:
  7. Parse and output:

Notes

Steps 4 and 5 can also be achieved on the template level as well.

The reason for calling the Markdown helper in the template and not in the action is due to Symfony's output escaper (and also because presentation logic belongs in the View). By default, SymfonyAconverts all html tags to entities, which is great for security, in case the input comes from an untrusted source. Had we parsed with Markdown at the controller level, you would have seen html tags in your browser. If, for any reason, you still wish to parse at the controller level, make sure to output using this code:A$sf_data-getRaw(acontent');

Here is a link to short and comprehensive Markdown Syntax Documentation.