4

Glass Mapper V3 を使用して、Sitecore アイテムが特定の Glass Mapper クラス/インターフェイスをサポートしているかどうかを確認できますか?

これらのクラスを考えると

[SitecoreType]
public partial interface IPage : IGlassBase
{
  // ... some properties here ...
}

[SitecoreType]
public partial interface IRateableItem : IGlassBase
{
  // ... some properties here ...
}

私はこのようなことをしたいと思います

var context = SitecoreContext();
var item = context.GetCurrentItem<IRateableItem>();
if (item != null)
  // it's an item that is composed of the Rateable Item template

残念ながら、そうすると、現在のアイテムがそのテンプレートで構成されているかどうかに関係なく、IRateableItem 型のアイテムが返されます。

4

3 に答える 3

2

このコードを使用して、Item を特定のタイプの Glass モデルとしてロードできるかどうかを判断しました。例として IRateableItem タイプを使用しました。

public void Main()
{
    var item = Sitecore.Context.Item;

    if (item.TemplateID.Equals(GetSitecoreTypeTemplateId<IRateableItem>()))
    {
        // item is of the IRateableItem type
    }
}

private ID GetSitecoreTypeTemplateId<T>() where T : class
{
    // Get the GlassMapper context
    var context = GetGlassContext();

    // Retrieve the SitecoreTypeConfiguration for type T
    var sitecoreClass = context[typeof(T)] as SitecoreTypeConfiguration;

    return sitecoreClass.TemplateId;
}

private SitecoreService GetSitecoreService()
{
    return new SitecoreService(global::Sitecore.Context.Database);
}

private Glass.Mapper.Context GetGlassContext()
{
    return GetSitecoreService().GlassContext;
}

編集:
この拡張メソッドを追加して、テンプレートが特定の基本テンプレートから継承されているかどうかを判断できるようにします。

public static bool InheritsFrom(this TemplateItem templateItem, ID templateId)
{
    if (templateItem.ID == templateId)
    {
        return true;
    }

    foreach (var template in templateItem.BaseTemplates)
    {
        if (template.ID == templateId)
        {
            return true;
        }

        if (template.InheritsFrom(templateId))
        {
            return true;
        }
    }

    return false;
}

だから今、あなたはこれを行うことができます:

if (item.Template.InheritsFrom(GetSitecoreTypeTemplateId<IRateableItem>()))
{
  // item is of type IRateableItem
}
于 2013-10-23T08:13:18.620 に答える