Allowing highlighted text in simple Sitecore text fields with truncate enabled

In our project, we came across a requirement where the content author wanted to manage text with highlights, and we also needed to be able to truncate this – to show as teasers in certain locations – to maintain the integrity of the design.

2015-07-05_155157

We initially thought of Rich Text fields – but then the business need was to ONLY allow highlighted text as special formats – and nothing else. And this was only for certain fields – so we certainly didn’t want to restrict the rich text editor itself either. Additionally allowing full blown html, made the truncation bit a little dicey.

So here’s the solution we came up with.

We picked a custom tag and had the content authors enter the text with those tags. For example, for the above image, the content managed in the sitecore field (single line or multiline – plain text field) was: [highlight]Test[/highlight] caption with [highlight]highlight[/highlight]

While rendering this field on the view:

2015-07-05_155935

In the above example, we not only transform the input text to include highlights, we are also keeping in mind page editor support, and further – we also limit the output text to a certain character count.

public static string GetHighlightedTextHtml(string textToTransform, int characterLimit = 0, bool appendEllipses = false)
        {
            if (string.IsNullOrWhiteSpace(textToTransform))
            {
                return string.Empty;
            }

            string rawText = textToTransform
               .Replace("[highlight]", string.Empty)
               .Replace("[/highlight]", string.Empty);

            characterLimit = TextUtilityStatic.TruncTextToSpecificNumOfChars(rawText, characterLimit).Length;

            string transformedHtml = textToTransform
                .Replace("[highlight]", "<em class=\"highlight--yellow\">")
                .Replace("[/highlight]", "</em>");

            if ((characterLimit > 0 && characterLimit >= rawText.Length) || characterLimit == 0)
            {
                return transformedHtml;
            }

            bool inTag = false;
            int textCharCounter = 0, htmlCharCounter = 0;

            foreach (Char c in transformedHtml)
            {
                if (c == '<')
                {
                    inTag = true;
                    htmlCharCounter++;
                    continue;
                }

                if (c == '>')
                {
                    inTag = false;
                    htmlCharCounter++;
                    continue;
                }

                if (inTag)
                {
                    htmlCharCounter++;
                    continue;
                }

                // Out of tag
                if (characterLimit <= textCharCounter)
                {
                    break;
                }
                htmlCharCounter++;
                textCharCounter++;
            }

            transformedHtml = transformedHtml.Substring(0, htmlCharCounter);

            if (inTag)
            {
                transformedHtml += "</em>";
            }

            return transformedHtml + (appendEllipses ? "..." : "");
        }

Additionally we have logic in place to truncate text to the given character limit – to the nearest word and optionally append ellipses to the text.

        public static string TruncTextToSpecificNumOfChars(string str, int maxCharCount, bool appendEllipses = false)
        {
            if (string.IsNullOrWhiteSpace(str)) return string.Empty;

            if (str.Length <= maxCharCount || maxCharCount == 0)
                return str;

            var originalStrLen = str.Length;

            if (str.Length > maxCharCount)
                str = str.Substring(0, maxCharCount + 1);

            var ellipsePos = str.LastIndexOfAny(new[] { ' ', '.', ',', ';', '!', '-', ']', '}', ')', '*' });
            if (ellipsePos != -1 && str.Length > ellipsePos && ellipsePos > 0)
                str = str.Substring(0, ellipsePos);

            if (ellipsePos == -1)
            {
                str = str.Substring(0, str.Length - 1);
            }

            if ((str.Length < originalStrLen) && appendEllipses)
            {
                str = str.TrimEnd('.').TrimEnd(',').TrimEnd(';').TrimEnd('-');
            }

            return str + ((str.Length < originalStrLen) && appendEllipses ? "..." : string.Empty);
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s