This week's TBB is Enforce Anchor Target TBB. The functionality is to enforce a 'system-wide' anchor target policy. Namely, any fully qualified URLs should open in a new (_blank) target browser window. All other (relative) URLs should open in the same target. More specifically, if there is a target specified for a relative URL, remove it.
Name
|
Enforce Anchor Target TBB
|
Type
|
· Template in .NET Assembly
|
Description
|
Used to:
· Enforces a certain “target” attribute for the
anchor tags depending on their “href” attribute value;
Notes:
This generic TBB expects an Item called “Output” in the
Package.
It parses the Output looking for anchor <a> tags. If
the anchor’s “href” attribute is a fully qualified URL (starts with “http://”
or “https://”), then it adds/replaces “target” attribute with value “_blank”.
Otherwise, it removes the “target” attribute, if present.
Finally the transformed Output is saved back into the
Package.
|
Parameters
|
n/a
|
Applicable to
|
Any template where an Item called
‘Output’ exists in the Package
|
The Code
[TcmTemplateTitle("Enforce
Anchor Target TBB")]
public class EnforceAnchorTarget : ITemplate
{
private const string
ANCHOR_REG_EXP = "<a[^>]*>";
private readonly Regex
imgRegExp = new Regex(ANCHOR_REG_EXP,
RegexOptions.IgnoreCase);
private readonly TemplatingLogger
log = TemplatingLogger.GetLogger(typeof(EnforceAnchorTarget));
public void Transform(Engine
engine, Package package) {
GenericUtils
utils = new GenericUtils();
Item
outputItem = package.GetByName(Package.OutputName);
string
xhtml = outputItem.GetAsString();
foreach
(Match match in
GetAnchorTags(xhtml)) {
string
anchorHtmlTag = match.Value;
string
anchorHref = utils.GetHtmlTagAttributeValue("href",
anchorHtmlTag);
if
(anchorHref == null) //
anchor without an href
{
continue;
}
string
target = anchorHref.ToLower();
if
(target.StartsWith("http://") ||
target.StartsWith("https://")) {
utils.SetHtmlTagAttribute("target", "_blank",
ref anchorHtmlTag);
} else
{
utils.RemoveHtmlTagAttribute("target", ref
anchorHtmlTag);
}
xhtml = xhtml.Replace(match.Value,
anchorHtmlTag);
}
outputItem.SetAsString(xhtml);
}
private MatchCollection GetAnchorTags(string xhtml) {
return
imgRegExp.Matches(xhtml);
}
}
Comments