Wrapping tables in TinyMCE with a div

PLACE FOR BLOG

Wrapping tables in TinyMCE with a div

Wrapping tables in TinyMCE with a div

marija

While developers usually manage to explain the downsides of using table inside TinyMCE, at times, client requirements and budget constraints push us to enable it. Still, at least the basic responsiveness is required.

The simplest scenario is to wrap the table tag in a div with a Bootstrap class (if you are using Bootstrap). This is ofc possible with js, but it's easy enough to serve the correct HTML directly from backend.

This very simple code snippet simply replaces all occurrences of table tag with a wrapping div. (table tag might contain additional attributes, so simplest is to just replace an open tag.)

if (xHtmlString?.Fragments != null)
{
    var sb = new StringBuilder();

    foreach (var fragment in xHtmlString.Fragments.GetFilteredFragments())
    {
        if (fragment is StaticFragment staticFragment)
        {
            sb.Append(staticFragment.InternalFormat);

            sb.Replace("<table", "<div class=\"table-container\"><table");
            sb.Replace("</table>", "</table></div>");
        }
        else if (fragment is UrlFragment urlFragment)
        {
            var urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>();
            var urlBuilder = new UrlBuilder(urlFragment.InternalFormat);

            sb.Append(urlResolver.GetUrl(urlBuilder, ContextMode.Default));
        }
        else
        {
            sb.Append(fragment.InternalFormat);
        }
    }

    return new XhtmlString(sb.ToString());
}

return null;

Please note that the XhtmlString can contain several fragments: StaticFragment, UrlFragment, (Personalized)ContentFragment...

One should be aware that ex. image tag consists of and write any similar manipulations accordingly:

  • One StaticFragment, ex. img class="right-img" src="
  • One UrlFragment the URL to the image file, which needs to resolve the URL for view. Read more.
  • Closing img tag

LEAVE A COMMENT