Pass parameters to rendering using ItemRendering in Sitecore - sitecore

I have a rendering that calls its datasources children. Each child item has a rendering attached in the renderings field.
I am calling
#Html.Sitecore().ItemRendering(item)
Which works.
However I want to pass some parameters to the child's rendering, so I tried the following code;
#Html.Sitecore().ItemRendering(item, new { Parameters = "active=1" })
But the parameters do not get passed to the child rendering when I call #Html.Sitecore().CurrentRendering.Parameters["active"]
So I tried #Html.Sitecore().ItemRendering(item, new { Active = 1 }). I called it again in the child rendering and still no luck.
Is there a way to pass parameters to the child using #Html.Sitecore().ItemRendering()

The ItemRendering method does not seem to handle properties correctly (or as one would expect!).
A work-around is to use #Html.Sitecore().Rendering() instead. You can use this in the same way as the ItemRendering method with the work-around below. Note that you should be setting the "Renderers" field of the datasource item (or its template standard values) rather than the "Renderings" field as you mentioned:
#Html.Sitecore().Rendering(item["__Renderers"], new {Datasource = item.ID, Message = "Hello World"})
In the child rendering, use the Properties property, not Parameters:
#Html.Sitecore().CurrentRendering.Properties["Message"]

var viewData = new ViewDataDictionary();
viewData["active"] = "1";
Html.Sitecore().ItemRendering(ItemToRender, viewData);
In the rendering for the Item, you can access the viewdata like this:
(ViewData["active"] != null && int.Parse(ViewData["active"].ToString()) == 1)

Related

DART/FLUTTER: How to get access to member variable / values of Widgets

I have an list of widgets. The widgets are background images for a website. The last widget(image) in this list is displayed onscreen. As nav functions push/pop, the last element is removed/added.
One of the fields in the Widget(BackdropImage) is a bool called 'isForeground'. I need access to it.
Why? Some background images are foreground and are to be rendered above the site's semi-transparent background texture, some are to be rendered behind it.
If I have a List(BackDropImage) and the BackDropImage contains:
Path, BoxFit, Opacity, isForeground(bool) etc etc. How can I get access to the last BackDropImage in BackDropImage list and access its isForground field?
//PSUDO WIDGET TREE:
if(backdropImageList.last's 'isForground' field is FALSE) BackDropImage.last,//render here below the texture
BackgroundTextureWidget,
if(backdropImageList.last's isForground field is TRUE) BackDropImage.last //render here above the texture
HeadingWidget,
OtherWidgets
I'd appreciate help if possible (or alternative approaches). The alterative is to flip a bool programmatically every time a button is pressed/popped and keeping track of what images are displayed where. Knowing which images are fore/background in the first place and controlling from the object itself is much neater IMO.
Thanks folks.
list.firstWhere((x) => x['isForground'] == true);
Widget is an abstract class. When working with Widgets like Container etc that have member variables you need to access programmatically, it can be done like this:
Widget testContainer = Container (width:100)
print(testContainer.width) // WON'T WORK
print((testContainer as Container).width) // WILL WORK
To access the member variables of individual Widgets in a list of Widgets:
List<Widget> listOfWidgets = [Container(color:Colors.blue), Container(color:Colors.red), Container(color:Colors.green)]
void printColorsOfAllContainers () {
for (var element in listOfWidgets) {
if (element is Container) {
print(element.color);
}
}
}
Alternatively, you can also do things like this:
void printColorsOfAllContainers() {
final List<Color> listOfContainerColours = [];
for (var element in listOfWidgets) {
element as Container;
listOfContainerColours.add(element.color!);
}
}

Sitecore get all parent (ancestor) with little processing (performance)

I'm trying to come up with solution on getting all the ancestors for the context item. One option is to store _path in index and other option is to do similar to one below:
http://www.glass.lu/Blog/GettingAncestors
I'm having no luck with getting the solution work for above (glass mapper) solution.
I got the index solution working but would like to avoid using index just to get the _path (collection of ancestors) as we don't have any other requirements to use index e.g. search etc.
Appreciate if someone could share the snippet for working solution or even better if Glassmapper has already included the above blog solution.
The most efficient way to check if one item is a descendant of another is to simply check that the current item property Paths.LongID starts with the LongID of the parent item:
Item currentItem = Sitecore.Context.Item;
IList<Item> menuItems = GetMenuItems();
foreach (var menuItem in menuItems)
{
bool isActive = currentItem.Paths.LongID.StartsWith(menuItem.Paths.LongID);
// do code
}
This will work since the path GUIDs are unique for each item.
Alternatively, if you want to use Glass models only then you can use the SitecoreInfoType.FullPath attribute:
[SitecoreInfo(SitecoreInfoType.FullPath)]
public virtual string FullPath { get; private set; }
And then from your code you can simply check:
Item currentItem = Sitecore.Context.Item; //or use SitecoreContext() to get a strongly types model
IEnumerable<MenuItem> menuItems = GetMenuItems();
foreach (var menuItem in menuItems)
{
bool isActive = currentItem.Paths.FullPath.StartsWith(menuItem.FullPath);
// do code
}
Just a word of warning, since each menu item now need code to run in order to determine state, this will make your menu component difficult to cache, resulting caching too many variations or caching per page. You would be better to move this logic into Javascript to set the menu state using the current page URL, this will allow your component to be cached once for all pages.

Sitecore 8: Automatically fill a placeholder by a default rendering

I was playing around with dynamic placeholders and was struck by a prefilling concept.Is there a way to select a default rendering for one of my placeholders which would avoid the "select rendering" dialog in experience editor ??
Scenario: I have a rendeing called "PageHead" which has three renderings. One of them is a placeholder "PageTeaserPh" which currently allows two renderings: one is "PageTeaser" and second "PageTeaserWithImage". I want the placeholder "PageTeaserPh" to always have the rendering selected as "PageTeaser" and therefore avoid the dialog "Select rendering" .
I did some homework and was wondering if this is something related to Standard values (we can have it at template level; not sure for renderings though) and also i have heard of command template concept (not in-depth).
Any and all help appreciated.
You can have renderings assigned on standard values of templates, each new item would then have your PageTeaser rendering.
If you wanted to automate this process have a look at the <mvc.getXmlBasedLayoutDefinition> pipeline, we are injected common renderings by extending this pipeline.
Updated
I've found some code samples and blog posts that should help point you in the right direction for manipulating the layout details.
public void AddSublayoutToItem(string itemId, string sublayoutId)
{
using (new Sitecore.SecurityModel.SecurityDisabler())
{
if (Sitecore.Data.ID.IsID(itemId) && Sitecore.Data.ID.IsID(sublayoutId))
{
//Get the master database and get the item on which you want to add sublayout
Database masterDatabase = Database.GetDatabase("master");
Item item = masterDatabase.GetItem(Sitecore.Data.ID.Parse(itemId));
// Or you can also get Sitecore Item from Context Database as per your requirement
// Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse(itemId));
if (item != null)
{
// Get the layout definitions and the device definition
LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());
//Create a RenderingDefinition and add the reference of sublayout or rendering
RenderingDefinition renderingDefinition = new RenderingDefinition();
renderingDefinition.ItemID = sublayoutId;
//Set placeholder where the rendering should be displayed
renderingDefinition.Placeholder = "content";
// Set the datasource of sublayout, if any
renderingDefinition.Datasource = "{24240FF2-B4AA-4EB2-B0A4-63E027934C38}";
// you can also set datasource of sublayout using Sitecore Path
// renderingDefinition.Datasource = "/sitecore/content/Home/Books";
//Add the RenderingReference to the DeviceDefinition
deviceDefinition.AddRendering(renderingDefinition);
// Save the layout changes
item.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml(); ;
item.Editing.EndEdit();
}
}
}
}
Taken from here - http://www.bugdebugzone.com/2014/06/how-to-add-sublayout-to-sitecore-item.html
Also a couple of other blogs on the topic

data-dialog created dynamically

I'm using polymer 1.0.
I'm trying to open a with on a clic on an element created dynamically with template repeat.
Here is the code :
<paper-button
data-dialog="modal"
on-click="dialogClick">
Click
</paper-button>
and the script (from doc) :
dialogClick: function(e) {
var button = e.target;
while (!button.hasAttribute('data-dialog') && button !== document.body) {
button = button.parentElement;
}
if (!button.hasAttribute('data-dialog')) {
return;
}
var id = button.getAttribute('data-dialog');
var dialog = document.getElementById(id);
alert(dialog);
if (dialog) {
dialog.open();
}
}
This work only if the value of data-dialog is simple text. If I want to change it by data-dialog="{{item.dialogName}}" for instance, it doesn't work. It is not found by the while loop and exit with the if. in the source code of the page, there is no data-dialog in the paper-button.
Any idea ?
I've ran into a similar problem when using data attributes on custom elements. You might want to subscribe to this polymer issue.
As a workaround, place the data attribute in a standard element that is a parent of the button and search for that one instead.
Also, you might want to consider using var button = Polymer.dom(e).localTarget instead of directly accessing e.target, since the later will give you an element deeper in the dom tree under shady dom.

Sitecore, render Item in code with personalization in mvc

My terminology might be slightly off as I am new to Sitecore mvc. I am trying to hardcode a view rendering with a hard coded datasource (I have to do it this way for other requirements) This view rendering has placeholders that are dynamically set and then personalized.
How can I trigger the ViewRendering on an item?
I've tried ItemRendering, but it doesn't seem to be picking up the stuff set up in the PageEditor.
* To be clear, the helpful posts below have the rendering working, but we do not seem to be getting the personalized datasources. *
I believe this is what you're after:
Item item = /* think you already have this */;
// Setup
var rendering = new Sitecore.Mvc.Presentation.Rendering {
RenderingType = "Item",
Renderer = new Sitecore.Mvc.Presentation.ItemRenderer.ItemRenderer {
Item = item
}
};
rendering["DataSource"] = item.ID.ToString();
// Execution
var writer = new System.IO.StringWriter();
var args = new Sitecore.Mvc.Pipelines.Response.RenderRendering(rendering, writer);
Sitecore.Mvc.Pipelines.PipelineService.Get().RunPipeline("mvc.renderRendering", args);
// Your result:
var html = writer.ToString();
You can statically bind a View Rendering using the Rendering() method of the Sitecore HTML Helper. This also works for Controller Renderings using the same method.
#Html.Sitecore().Rendering("<rendering item id>")
This method accepts an anonymous object for passing in parameters, such as the Datasource and caching options.
#Html.Sitecore().Rendering("<rendering item id>", new { DataSource = "<datasource item id>", Cacheable = true, Cache_VaryByData = true })
In your view rendering, I am assuming you have a placeholder defined along with the appropriate placeholder settings in Sitecore (If not, feel free to comment with more detail and I will update my answer).
#Html.Sitecore().Placeholder("my-placeholder")
In this case, "my-placeholder" will be handled like any other placeholder, so you will be able to add and personalize components within it from the Page Editor.