Developer forum

Forum » Templates » Can you test if snippet is empty?

Can you test if snippet is empty?

Gitte Simonsen
Reply

This way:

@if( if snippet isn't empty ){

  @RenderSnippet("snippet")

} else {

  <p>Do something else</p>

}


Replies

 
Nicolai Høeg Pedersen
Reply

Hi Gitte

Since snippets are not a real template tag the values do not live in the template instance and cannot be used in conditionals.

Also a snippet destination is usually in the header, and the data comes from i.e. a module. So at the time of execution, the header is rendered before the content and conditional would not make sense.

So, what to do?

You are using Razor - that opens some possibilities.

In your whatever template (paragraph or module template) you can add information to the HttpContext item collection and use them i.e. in your layout template.

I.e. module template:

@{
System.Web.HttpContext.Current.Items["mysnippetname"] = "Here is some data";
}

And then use it in the layout template:

@System.Web.HttpContext.Current.Items["mysnippetname"]

This works in the same way as the viewbag in MVC

BR Nicolai

 

You must be logged in to post in the forum