Escaping URLs for XHTML
Question:
From: Charles Wiltgen
MT is great, but it was a bit of an effort to get it doing validated XHTML. One piece that’s missing is something that would fix URLs in entries. For example, ampersands in URLs apparently need to be changed to “&”, which seems difficult since you don’t want to change ampersands in “&”s in URLs. Can any of your wonderful plug-ins be used to address this?
Brad Answers:
Why of course they can! The following should do the trick:
<MTRegexDefine name="escapeamp">s/&(?!amp;)/&/g</MTRegexDefine>
<MTMacroDefine name="escapfiy" ctag="a">
<MTIfNotEmpty expr="[MTMacroAttr name='href']">
<MTMacroAttr name="href"
value="[MTMacroAttr name='href' regex='escapeamp']">
</MTIfNotEmpty>
<MTMacroTag rebuild="1"><MTMacroContent></a>
</MTMacroDefine>
Then, apply the macro to whatever MT tags you’d like, such as:
<$MTEntryBody apply_macro="escapify"$>
or
<MTMacroApply macro="escapify">
<$MTEntryBody$>
<$MTEntryMore$>
</MTMacroApply>
Naturally, this solution requires you install both the Regex and Macro plugins. It will reformat the ‘href’ attribute of your ‘a’ tags by amending any ‘&’ characters that aren’t already escaped. This is a good and a bad thing. The good thing is that it makes sure that all your entries have properly escaped ampersand characters in any hyperlinks you define.
The bad thing is that it allows you to continue to write invalid XHTML. Another way to go about this is to have Movable Type give you an error whenever it sees you have a invalid hyperlink. Like so:
<MTMacroDefine name="urlcheck" ctag="a">
<MTIfMatches expr="[MTMacroAttr name='href']" pattern="m/&(?!amp;)/">
<MTDie>You have unescaped ampersands in this
hyperlink: <MTMacroAttr name="href"></MTDie>
</MTIfMatches>
<MTMacroTag rebuild="1"><MTMacroContent></a>
</MTMacroDefine>
And apply this ‘urlcheck’ macro in the same manner I’ve described. This solution requires the Warn/Die plugin in addition to ‘Regex’ and ‘Macro’.
[ Movable Type ] / posted @ Monday, January 13, 2003 6:38 PM EST