Search code examples
htmltemplatesexpressionengine

Remove White Space from ExpressionEngine Templates


I was wondering if there was a way to strip the extra white space created by EE's template system and produce "prettier" markup.

I like to keep my templates readable. I often times come back to jobs years later, have to follow other developers' work, or work as part of a team, and it's easier when everything is neat and nested.

The problem is that EE preserves all of the tabs and line breaks, and when you have a lot of conditionals and such, it results in ugly code. For example, this:

<div class="
    event {if event_all_day}all_day{/if} 
    {if event_multi_day}multi_day{/if} 
    {if event_first_day}first_day{/if} 
    {if event_last_day}last_day{/if} 
    {if all_day_event_index_difference > 0}index_difference_{all_day_event_index_difference}{/if}
">
    {if event_multi_day} 
        <a href="{path='calendar_main/event'}/{event_id}/">{event_title}</a>
    {if:else}
        <a href="{path='calendar_main/event'}/{if edited_occurrence}{event_parent_id}{if:else}{event_id}{/if}/" title="{event_title}">{event_title}</a>
    {/if}
</div>

Renders into this:

<div class="
                                         event all_day 
                                         multi_day 


                                                                               ">

                                         <a href="http://www.downtownmuncie.org/calendar_main/event/1832/">Minnetrista Glass Show</a>
                                                                       </div>

Every tab and line-break surrounding the EE tags is preserved, so I wind up with a mile of white space between the <div> and </div>.

Performance-wise, it doesn't mean a thing. There may be an argument to be made for an increase in file size, but it's negligible. It's also a bit of a hinderance when trying to navigate through the code using Firebug.

But most of all, it just looks sloppy.

One suggestion is to adjust the templates accordingly, like so:

<div class="event {if event_all_day}all_day {/if}{if event_multi_day}multi_day {/if}{if event_first_day}first_day {/if}{if event_last_day}last_day {/if}{if all_day_event_index_difference > 0} index_difference_{all_day_event_index_difference}{/if}">
    {if event_multi_day}<a href="{path='calendar_main/event'}/{event_id}/">{event_title}</a>{if:else}<a href="{path='calendar_main/event'}/{if edited_occurrence}{event_parent_id}{if:else}{event_id}{/if}/" title="{event_title}">{event_title}</a>{/if}
</div>

That's not really a viable solution. Given the choice between neat templates and neat code, I'd have to go with the former.

Is there any way to have both?

ty


Solution

  • There is the tidy_template extension that uses the template_post_parse hook in EE, assuming you have 2.4.0 or newer.

    https://github.com/sjelfull/sf.tidy_template.ee_addon