你有幾個選項提供給你,我會建議的根據您的需要的東西的組合,但你也想在各方面被防守編碼,因爲內容創作者必須做的事情,他們不應該的潛力!
您可以爲你的模板一些默認值,使他們始終有一個初始值。有了您的模板中選擇和生成器標籤強調,從色帶選擇選項選項卡,然後添加標準值
一個新項目稱爲__Standard Values
將模板下加入,你可以在那裏設置默認值。請確保您設置了您的渲染Datasource Location
和Datasource Template
領域,這將導致the prompt to create/select datasource item。
你仍然需要防守的代碼雖然。你如何做到這一點取決於你。例如,如果某些字段設置不正確,那麼也許你不顯示在所有組件或返回不同的視圖來顯示它是不正確的:
public class WidgetController : GlassController
{
public ActionResult Index()
{
var configItem = GetDataSourceItem<ILocationConfiguration>();
if (configItem.Longitude == null && configItem.Latitude == null)
return PartialView("~/Views/Components/Shared/IncorrectSettings.cshtml");
return PartialView("~/Views/Components/Widget/Index.cshtml", configItem);
}
}
(以上樣品用Glass Mapper,我知道你是沒有使用它,但我會強烈推薦它或在任何情況下使用strongly types models。)
你也可以在視圖本身做一些檢查,但我不會在這裏放太多的代碼我。根據組件的不同,有時我們不會在體驗編輯器模式下顯示渲染的組件。下面的示例允許在EE模式要被編輯的值,但是如果值已被設定使得該腳本塊和部件:
@model Sitecore.Mvc.Presentation.RenderingModel
@if (!Model?.Item?.TemplateID=="guid" ?? true)
{
@Html.Raw("<div class=\"error\">Incorrect Datasource</div>")
return;
}
@if (Sitecore.Context.PageMode.IsExperienceEditor)
{
<!-- This allows component settings to be edited in EE mode -->
<div>
Longitude: @Html.Sitecore().Field("lng", Model.Item)
Latitude: @Html.Sitecore().Field("lat", Model.Item)
Zoon: @Html.Sitecore().Field("zoom", Model.Item)
</div>
}
else
{
string lng = Model.Item["lng"],
lat = Model.Item["lat"],
zoom = Model.Item["zoom"];
if (!string.IsNullOrEmpty(lng) && !string.IsNullOrEmpty(lat) && !string.IsNullOrEmpty(zoom))
{
<script>
var options = { lat: @lat, lng: @lng, zoom: @zoom }
</script>
<div>
set up the component in normal mode
</div>
}
}
有許多不同的方式來實現上述包括在JavaScript本身,使檢查你如何調用你的組件的代碼,但我試圖保持它自包含和簡單的例子。
你使用視圖還是控制器渲染?如果你正在使用Controller,可能要檢查'RenderingContext.Current.Rendering.Datasource'是否爲空,否則請使用另一個視圖,說明「請設置數據源」。確認您是否正在使用數據源,然後用樣本回答。 – jammykam
感謝您的回覆。我正在使用控制器渲染。我使用渲染Item @Model,並設置了一個數據源(在它的樹中的路徑)來選擇一個內容項目。但JavaScript將失敗,因爲它首先呈現控制器視圖,然後拉動相關的項目... – David
好的。聽起來像你可以設置一些'__Standard值在你的項目默認爲_something_時,它是第一次創建,或使您的Javascript更具防禦性,當使用值... – jammykam