问题
I am trying to add a css class if I am in a particular layer.
So 2 questions:
Is it possible to identify the current layer in a Razor view. Something like:
if(currentLayer == "TheHomepage") { ... }
Is the the right way to approach HTML conditional on layer, or is there a better way to do this in Orchard?
回答1:
If you need to see which layers are currently active, you can do something like this:
@using Orchard.Widgets.Services
@{
var widgetsService = WorkContext.Resolve<IWidgetsService>();
var ruleManager = WorkContext.Resolve<IRuleManager>();
var activeLayerNames = new List<string>();
foreach (var layer in widgetsService.GetLayers()) {
try {
if (ruleManager.Matches(layer.LayerRule)) {
activeLayers.Add(layer.Name);
}
} catch(Exception ex) {
// Problem occurred during layer rule evaluation.
// Just treat it as though the layer rule did not match.
}
}
if (activeLayerNames.Contains("TheHomePage")) {
/* ... Your code here ... */
}
}
Much of the code above makes more sense in a driver or controller, but if you are working only in the view layer, you can do it this way.
回答2:
You can create a widget that includes the needed @{Style.Include}
statements and then add it to a layer.
Follow this instructions to create a new Widget using razor code: Creating simple custom Orchard widgets, name the new widget CssIncluder
Then add this view to your theme, you can use the Shape tracing tool if you like:
Widget-CssIncluder.cshtml:
@{
Model.Metadata.Wrappers.Clear();
Style.Include("somestyle.css");
}
Finally add the widget to the layer of your choice. Be sure to uncheck the title rendering option to get clean code.
回答3:
Based on Katsuyuki's answer, I created an extension method for WorkContext to convert all active layers into css classes.
using Orchard;
using Orchard.Widgets.Services;
using System.Collections.Generic;
namespace KidsMinistryTeam.Theme.Extensions
{
static public class WorkContextExtensions
{
static public IList<string> GetLayerCssClasses(this WorkContext workContext)
{
var widgetsService = workContext.Resolve<IWidgetsService>();
var ruleManager = workContext.Resolve<IRuleManager>();
var classNames = new List<string>();
foreach (var layer in widgetsService.GetLayers())
{
try
{
if (ruleManager.Matches(layer.LayerRule))
{
classNames.Add(string.Format("{0}-layer", layer.Name.ToLower())); //add any additional class sanitizing logic here
}
}
catch
{
}
}
return classNames;
}
}
}
Then by adding it to Model.Classes in my theme's Layout.cshtml I am now able to style based on active layers.
foreach(string className in WorkContext.GetLayerCssClasses())
{
Model.Classes.Add(className);
}
来源:https://stackoverflow.com/questions/20571844/orchard-cms-conditional-css-class-based-on-layer