Best Practice for Simple Webpart/Widget without needing code behind

Senior Software Engineer - Kentico Xperience MVP

Trevor Fayas asked on February 13, 2015 15:45

Hey all. It seems a common task sometimes to need to create a simple widget that takes a handful of parameters and spits them out in a specific way. In this example i have a banner image widget that takes a link, description, and 3 images (large, medium, and mobile), and just spits it out in a certain format.

What's the best way of going about this without needing to create code behind files and such? I have 'hacked' it in the past by making a widget from other webparts, and 'reusing' fields (or making a web part with a blank layout) and then setting the Widget Container to a container and putting the 'transformation' in the container.

Example Web part Layout acting as a transformation:

  <a href="{%if(Url.Length == 0) { return "#"; } else { return Url; }#%}">
  <img class="desktopShow" src="{%LargeImage%}" alt="{%Title.Replace("\"","''")#%}" />
  <img class="mobileShow" src="{%SmallImage%}" alt="{%Title.Replace("\"","''")#%}" />
  <img class="IpadShow" src="{% if(MediumImage.Length == 0) { return LargeImage; } else { return MediumImage; }#%}" alt="{%Title.Replace("\"","''")#%}"/>

Is there something already in Kentico that does similar? Is there a way to easily call the Web Part Fields from the Web Part Layouts (i can make a widget with a preset layout then)? Just looking for what would be best. Thanks!

Recent Answers

Brenden Kehren answered on February 14, 2015 18:03

Hey Trevor!

Widgets inherit the properties of a webpart so a webpart is needed. You can create a webpart in the UI with properties but unless there is code behind your values won't stick. So you need code.

One thing you could do is create an all inclusive webpart that has multiple properties for it and simply do as you're stating with the different layouts and such. Then you can also create multiple widgets from it too. Nice part about this approach is you have one webpart with simple properties to set that can be used all over.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.