【问题标题】:Glass Mapper breaking standard values for image fieldGlass Mapper 打破图像字段的标准值
【发布时间】:2016-10-16 22:46:05
【问题描述】:

考虑模板:

公司

  • 徽标(图像字段)
  • 公司名称(文本字段)

Company 模板在两个字段上都设置了标准值。如果我们得到一个 Company 项目并使用 Glass 保存它而不做任何更改,则 Logo 字段不再使用标准值。 (Company Name 字段保持不变。)

问题似乎在于,Glass.Mapper.Sc.DataMappers.SitecoreFieldImageMapper 序列化该字段的值与 Sitecore 不同。当它试图保存时,它认为这是对字段的更改,不再使用标准值。

标准值:

<image mediaid="{GUID}" />

玻璃产生的价值:

<image height="64" width="64" mediaid="{GUID}" alt="Alt text" />

有没有办法让 Glass 生成与 Sitecore 相同的输出?

【问题讨论】:

    标签: asp.net sitecore sitecore8 glass-mapper


    【解决方案1】:

    我认为问题在于SitecoreFieldImageMapper 如何将 ImageField 映射到 Image。为了获取 HeightWidthAlt 使用公共属性。如果我们通过反射器查看它们,我们会发现它的值不是直接来自字段:

    public string Alt
    {
        get
        {
            string text = base.GetAttribute("alt");
            if (text.Length == 0)
            {
                Item item = this.MediaItem;
                if (item != null)
                {
                    MediaItem mediaItem = item;
                    text = mediaItem.Alt;
                    if (text.Length == 0)
                    {
                        text = item["Alt"];
                    }
                }
            }
            return text;
        }
        set
        {
            base.SetAttribute("alt", value);
        }
    }
    

    如果字段不包含值(例如对于“alt”:if (text.Length == 0)),则将从链接的 MediaItem 接收值。它会导致在保存字段后从媒体库项目中添加 HeightWidthAlt

    要解决此问题,您可以尝试替换此代码:

    int height = 0;
    int.TryParse(field.Height, out height);
    int width = 0;
    int.TryParse(field.Width, out width);
    
    img.Alt = field.Alt;
    img.Height = height;
    img.Width = width;
    

    直接获取属性而不是使用属性:

    int height = 0;
    if(int.TryParse(field.GetAttribute("height"), out height))
    {
        img.Height = height;
    }
    
    
    int width = 0;
    if(int.TryParse(field.GetAttribute("width"), out width))
    {
        img.Width = width;
    }
    
    img.Alt = field.GetAttribute("alt");
    

    有了 Alt 属性,一切都应该没问题。但是 WidthHeight 可能存在问题,因为它们不是 Nullable 并且我不确定 GlassMapper 将如何处理具有 Width 的图像>高度您尚未设置。

    【讨论】:

    • 您是否建议创建自定义 ImageMapper 并按照您的答案更新这些属性,或者我将在哪里实际添加该代码?
    • 是的,我建议创建一个自定义 ImageMapper,因为存在问题。我不确定您是否能够使用配置文件来配置使用 ImageMapper。但是 GlassMapper 是开源的,您可以在 GitHub 上创建源代码,进行更改并使用新的 ImageMapper 获得新的程序集。 github.com/mikeedwards83/Glass.Mapper
    • 我建议你继承SitecoreFieldImageMapper,用你的实现覆盖get方法,然后注册CreateResolverjammykam.wordpress.com/2015/11/09/…,而不是克隆repo和构建,然后你可以在as上使用它- 必需的基础。请务必阅读文章的第 1 部分。
    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多