1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Sitecore; using Sitecore.Data; namespace Concentra.Web.Configuration.Pipelines.ExpandShortcodes { /// <summary> /// Expands shortcodes with the following format: /// [item id=110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9 fieldname="Title"] /// </summary> public class ExpandItemShortcodes : ExpandShortcodesProcessor { public override IEnumerable<Shortcode> GetShortcodes( string content) { if (String.IsNullOrWhiteSpace(content)) { return new List<Shortcode>(); } var shortcodes = new List<Shortcode>(); var matches = Regex.Matches(content, @"\[item id=(?<id>.*) fieldname=(?<fieldname>.*)\]" , RegexOptions.Compiled | RegexOptions.IgnoreCase); foreach (var match in matches.OfType<Match>().Where(m => m.Success)) { shortcodes.Add( new Shortcode { Unexpanded = match.Value, Expanded = GetItem( match.Groups[ "id" ].Value, match.Groups[ "fieldname" ].Value) } ); } return shortcodes; } public string GetItem( string id, string fieldName) { if (!String.IsNullOrEmpty(id) && ID.IsID(id)) { var item = Context.Database.GetItem(ID.Parse(id)); if (item != null ) { var name = fieldName.Replace( "\"" , String.Empty).Replace( "'" , String.Empty); if (item.Fields.Any(field => field.Name == name)) { return item.Fields[name].Value; } } } return String.Empty; } } } |
Wednesday, September 11, 2013
Sitecore Generic Shortcodes
I really enjoyed reading Sitecore Junkie's post about using Shortcodes in Sitecore. Here's an example of one I built for generic item shortcodes.
Labels:
sitecore
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment