brettbrewer.com

Programming + Design

Home arrow Tips & Tricks arrow Javascript Tips & Tricks arrow Making mustache tags play nice with CKEditor
Making mustache tags play nice with CKEditor PDF Print E-mail
Written by Brett Brewer   
Wednesday, 26 February 2014

I'm working on a CMS for a client and ran into the problem of needing to use nested conditional mustache tags in my site content. I'm using CKEditor to give the customer a nice UI for editing pages, but for some of the dynamic content, it requires putting mustache tags in the html code that is editable by the customer. When resaving the content it munges up all the witespace and indentation, making it a real pain to re-edit the html source if I need to go back in and make changes. Enter the CKEditor protectedSource config option. Since empty or undefined mustache tags are simply ignored by mustache and parsed out of the final output, you can use a little trick to protect the whitespace and other tags inside some simple delimiters. Simply add something like this to your CKEditor config:

CKEDITOR.config.protectedSource.push( /{{start_protect}}[^]+{{end_protect}}/g );

Then in your source view in CKEditor you can simply surround anything you don't want it to touch with:

{{start_protect}}
your custom code here
{{end_protect}}

There's just one caveat -- this doesn't work inside tables in your source code. I'm not sure if this is only if you have the CKEditor table plugin enable, or if it always happens with tables, but mustache conditionals somehow get stripped out of tables and placed above the table with all their contents emptied. I haven't found a way around this yet, so I switched my tables to divs and now it works -- my conditionals are where they are supposed to be and whitespace is preserved for ease of editing later. 

Last Updated ( Wednesday, 26 February 2014 )
 
Next >
© 2017 www.brettbrewer.com
Joomla! is Free Software released under the GNU/GPL License.