Search code examples
widgetorchardcmsprojection

Hide projection widget if query has no results


We are building a website with the Orchard CMS where we have campaign adds. These adds are linked to pages through tags (not the orchard tag part).

Then we built a custom filter that take these tags into consideration when fetching the campaign adds and display them in a widget.

On some pages there are tags but no campaigns that match these tags. We would like to hide the widget at this point.

One solution is to edit the widget layer every time a new campaign is added. But I would like to have a more solid solution than this.

Summary:
We would like to hide the entire projection widget when the query returns an empty result.

// Madelene


Solution

  • Most of the markup in the widget is rendered by the Widget.Wrapper.cshtml template. What you can do is filter what this wrapper will render based on the content of the widget itself. This way if the widget doesn't render anything, you can decide to hide the title and the other zones. Here is the code doing it:

    @using Orchard.ContentManagement;
    @using Orchard.Widgets.Models;
    @{
        var widgetPart = ((IContent)Model.ContentItem).As<WidgetPart>();
        var tag = Tag(Model, "article");
        var childContent = Display(Model.Child);
    }
    
    @if (!String.IsNullOrEmpty(Convert.ToString(childContent))) {
        @tag.StartElement
        if ((widgetPart.RenderTitle && HasText(widgetPart.Title)) || Model.Header != null) {
        <header>
            @if ((widgetPart.RenderTitle && HasText(widgetPart.Title))) {
            <h1>@widgetPart.Title</h1>
        }
            @Display(Model.Header)
        </header>
        }
        @childContent
        if (Model.Footer != null) {
        <footer>
            @Display(Model.Footer)
        </footer>
        }
    @tag.EndElement
    }
    

    Just create a file named Widget.Wrapper.cshtml in your theme and paste this content. You can check what was the previous content if you want to understand how it's done.