Skip to content

Instantly share code, notes, and snippets.

@greggnakamura
Last active April 6, 2021 20:41
Show Gist options
  • Save greggnakamura/817caeda46d2c7ad1660 to your computer and use it in GitHub Desktop.
Save greggnakamura/817caeda46d2c7ad1660 to your computer and use it in GitHub Desktop.
Kentico: Misc examples
/* Transformation Examples */
// Ternary example
<%# !string.IsNullOrEmpty((string)Eval("ItemToTest")) ? "True" : "False" %>
<%# !String.IsNullOrEmpty(Eval("ItemToTest").ToString()) ? "True" : "False" %>
<%# !string.IsNullOrEmpty((string)Eval("CatalogLink")) ? "<p>For detailed curriculum and more, please visit the <a href=\"" + Eval("CatalogLink") + "\" target=\"_blank\">Course Catalog entry</a> for this program.</p>" : Eval("CatalogDescription") + "<br /><br /><strong>For detailed curriculum and more please visit the <a onclick=\"_gaq.push(['_trackEvent', 'Link', 'Click' 'Course Catalog Adult Education'])\" target=\"_blank\" href=\"" + Eval("CatalogLink") + "\">Course Catalog entry</a> for this program.</strong><br />" %>
<%# !String.IsNullOrEmpty(Eval("ScheduleOfBenefitsDownload").ToString()) || !String.IsNullOrEmpty(Eval("ProviderNetwork").ToString()) ? "<strong>Resources</strong><br>" : "" %>
/* ********** */
// IfEmpty
<%# IfEmpty(Eval("Image"), "", "<img src=\"" + Eval("Image") + "\" class=\"alignright\" alt=\"" + Eval("DocumentName") + "\" />") %>
<%# IfEmpty(Eval("Download"), "", "<a href=\"" + Eval("Download") + "\" class=\"btn icon-download\" target=\"_blank\">Download</a>") %>
{% if (!String.IsNullOrEmpty(DocumentPageDescription)){ %}
<p>{% DocumentPageDescription %}</p>
{% } #%}
/* ********** */
// Transformation: RegexReplace()
{%
replacedString = RegexReplace(FieldName, @"[^0-9a-zA-Z\._]", string.Empty);
return;
#%}
<p>{% replacedString %}</p>
/* ********** */
// Transformation: documents at specific path, classname
{%
professional = Documents["/professional/Home"];
professionalChildren = professional.Children.Where("ClassName = 'OU.CampusLocationHomepage'");
return;
#%}
<ul>
{% professionalChildren.WithAllData.ApplyTransformation("OU.Transformations.MainNavigation_Level_1") %}
</ul>
/* ********** */
// add 'active' class if
{%
onPath = IsDocumentOnSelectedPath();
isCurrent = IsCurrentDocument();
return;
#%}
<li class="nav-item{% if( isCurrent || onPath ) { " active" }#%}">
<a class="nav-link" href="{% NodeAliasPath %}">
{% IfEmpty(DocumentMenuCaption, DocumentName, DocumentMenuCaption) %}
</a>
</li>
/* ********** */
// Macro Resolver
<a href="<%# CMSContext.ResolveMacros( Eval("URL").ToString() ) %>"><%# Eval("Name") %></a>
// Visbility
<p runat="server" Visible='<%# Eval<string>("Name") != "some-value" %>'>
<asp:Placeholder runat="server" ID="pl1" visible='<%# ... %>'>
...
</asp:Placeholder>
<asp:Placeholder runat="server" ID="pl2" visible='<%# !pl1.Visible %>'>
...
</asp:Placeholder>
<cms:QueryRepeater ID="qrConcentrations" runat="server"
Visible='<%# isCurrentPage(Eval<String>("nodeAlias"))%>'
QueryName="custom.DegreePrograms.GetConcentrationsBySchoolModalityAndCategory"
TransformationName="custom.degreeprograms.concentrations"
OrderBy="v1.DegreeName ASC"
PagerControl-PagerHTMLBefore="<li>"
PagerControl-PagerHTMLAfter="</li>">
</cms:QueryRepeater>
/* check if webpart contains content, hide if no content */
{% (ViewMode != "LiveSite") || (et_sc != null && et_sc.Trim() != "") #%}
{% if ((et_sc != null && et_sc.Trim() != "") == False) { "Full-width" } else { if ((et_sc != null && et_sc.Trim() != "") == True) { "two-column" } } #%}
{% if(OfficeShowStaff == True) { return true; } else { return false; } #%}
/* transformation: check if first record */
<%# DataItemIndex == 0 ? "First record" : "Not first record" %>
/* transformation: check if last record */
<%# DataItemIndex == DataRowView.DataView.Count - 1 ? "Last record" : "Not last record" %>
{% DataItemIndex == DataItemCount - 1 ? "Last record" : "Not last record" %}
/* transformation: `ApplyTransformation` */
{% Documents[NodeAliasPath].Children.WithAllData.ApplyTransformation("custom.VirtualMapImageGallery.CarouselGallery_Slide") #%}
{% Documents["/News"].Children.WithAllData.ApplyTransformation("custom.VirtualMapImageGallery.CarouselGallery_Slide") #%}
/* K# Examples */
// If statement
{% if (CurrentDocument.RelatedTitlesHeader == "") { "Related Books" } else { CurrentDocument.RelatedTitlesHeader } %}
{% if (bizFormField != null) { "<p>$$value:bizFormField$$</p>" } %}
// nested if statement
{% if (CMSContext.CurrentDocument.RelativeURL == "~/georgia/rate-quote") { GetResourceString("MHI.RateQuote.Georgia") } else { if (CMSContext.CurrentDocument.RelativeURL == "~/indiana/rate-quote") { GetResourceString("MHI.RateQuote.Indiana") } else { if (CMSContext.CurrentDocument.RelativeURL == "~/oklahoma/rate-quote") { GetResourceString("MHI.RateQuote.Oklahoma") } else { if (CMSContext.CurrentDocument.RelativeURL == "~/south-carolina/rate-quote") { GetResourceString("MHI.RateQuote.SouthCarolina") }}}} #%}
// escaping apostrophe in macro conditional
{% if (QueryString["DateSelected"]) { %}
CONVERT(date, EventDate) <= '{% QueryString["DateSelected"]|(handlesqlinjection)true %}' AND CONVERT(date, EventEndDate) >= '{% QueryString["DateSelected"]|(handlesqlinjection)true %}'
{% }|(handlesqlinjection)false
#%}
// select parent document name based on nodealiaspath
{% Documents[NodeAliasPath].Parent.DocumentName #%}
/* WebPart Visibility */
// Do NOT show if DocumentName is equal to "Home"
{%DocumentName|(notequals)Home|(truevalue){?param?}%}
// Do NOT show if NodeID is equal to "211"
{%NodeID|(notequals)211|(truevalue){?param?}%}
// Hide page(s) in the /Landing-Pages directory
{%CMSContext.CurrentDocument.NodeAliasPath|(Contains)Landing-Pages|(not)#%}
// Show if DocumentName is equal to "Home"
{%DocumentName|(equals)Home|(truevalue){?param?}%}
// Show if path contains
{%Contains(CMSContext.CurrentDocument.NodeAliasPath, "Landing-Pages")#%}
// Show if path does not contain
{%!Contains(CMSContext.CurrentDocument.NodeAliasPath, "Landing-Pages")#%}
{%not(Contains(CMSContext.CurrentDocument.NodeAliasPath, "Landing-Pages"))#%}
{% !EditedObject.NodeAliasPath.Contains("/Parts-Store") #%}
// Visibility based on Wildcard value
{%QueryString["County"] != ""%}
// Get QueryString value
{% QueryString.parameter %}
// Multiconditional
{% if (PortalContext.ViewMode == "Design") { return false; } else { if (PortalContext.ViewMode == "Edit") { return false } else { return true }} #%}
// Date format
<%# GetDateTime("BlogPostDate", "D") %>
{% CurrentDateTime.Year#%}
{% CurrentDocument.DocumentModifiedWhen.Format("{0:MM/dd/yyyy}") #%} /* 09/12/2016 */
{% CurrentDocument.DocumentModifiedWhen.Format("{0:T}") #%} /* 1:42:31 PM */
/* String replace */
// Kentico: Transformation, string replace, tolower
<%# Eval("DocumentName").ToString().Replace(" ", "-").ToLower() %>
/* kentico caching long lists of data */
items = Cache(GlobalObjects.CustomTables["BCLS.Reagents"].items);
items2 = Cache(GlobalObjects.CustomTables["BCLS.FlowInstrumentsAndSoftware"].items);
// Resolve Localization strings in transformation
<%# ResHelper.LocalizeString("{$Autobag.SpareParts.Btn_AddToRFQ$}") %>
PersonDivision LIKE '%{% QueryString["School"].ToString().Replace("-", " ").ToLower() %}%' and PersonIsFacultyLeader = 1
/* Get Custom Table data using macro */
{% GlobalObjects.CustomTables["customtable.SampleTable"].Items[3].GetValue("ItemText") %}
/* Set site to non-https from db */
update CMS_SettingsKey
set KeyValue='False'
where KeyName='CMSUseSSLForAdministrationInterface'
update CMS_Tree
set IsSecuredNode= NULL, RequiresSSL=NULL
/* jquery ajax call example */
$.ajax({
url: 'http://claremontsavings.com.w1.wfdev.net/rest/content/currentsite/all?classnames=claremont.LocationContentBlock&hash=94c0c05e0ee167c1e1d8999a52b6efe2170d0a5b07f3a8b02a138be0139c2555',
dataType: 'xml',
success: function(xml, status, xhr) {
$(xml).find('claremont_LocationContentBlock').each(function() {
var name = $(this).find('DocumentName').text();
var location = $(this).find('NodeAlias').text();
var zip = $(this).find('ZipCode').text();
$('<li>' + zip + ' - ' + name + ' (' + location + ')' + '</li>').appendTo('#zipCodes');
$('<p>' + zip + '</p>').appendTo('#rawData');
});
console.log('Status: ' + xhr.statusText);
},
error: function(xhr, status, error) {
console.log('Error occurred: ' + xhr.statusText);
}
});
/* Dates */
<%# FormatDateTime(Eval("EventDate"), "MMMM d") %>
<%# IfEmpty(Eval("EventEndDate"), "", IfCompare(FormatDateTime(Eval("EventDate"), "MMM d"), FormatDateTime(Eval("EventEndDate"), "MMM d"), " - " + IfCompare(Eval<DateTime>("EventDate").Month, Eval<DateTime>("EventEndDate").Month, FormatDateTime(Eval("EventEndDate"), "MMMM d"), FormatDateTime(Eval("EventEndDate"), " d")), "")) %>
/* Format Numbers */
<%# String.Format("{0:n}", Int64.Parse(Eval("Field").ToString())) %> // 100,000.00
<%# String.Format("{0:n0}", Int64.Parse(Eval("Field").ToString())) %> // 100,000
<%# String.Format("{0:C}", Eval("TotalPriceIncludingOptions")) %>
/* sql */
/* populate dropdowns */
SELECT Code as Value, Code as Name FROM MyCodeTable
SELECT Location AS Code, Location FROM customtable_ConferenceLocations
SELECT REPLACE(Location, ' ','-') AS Code, Location FROM customtable_ConferenceLocations
SELECT '' AS Code, '-- Select Location --' AS Location
UNION
SELECT Location AS Code, Location
FROM customtable_ConferenceLocations
/* get document by categories */
SELECT DocumentName
FROM View_CMS_Tree_Joined
WHERE DocumentID IN (Select DocumentID FROM CMS_DocumentCategory WHERE CategoryID in (Select CategoryID from CMS_Category where CategoryName IN ('News', 'FAQs')))
/* Custom table control settings */
Custom table item selector form control: https://www.screencast.com/t/slxjPobM
/* transformation: custom variable */
{%
myVariable = ( !String.IsNullOrWhiteSpace( DocumentMenuCaption ) ) ? DocumentMenuCaption : DocumentName;
return;
#%}
<a href="GetDocumentUrl()">{% myVariable %}</a>
/* pipe delimited list */
{% if (!String.IsNullOrEmpty(LocationFeaturesList)) { %}
<ul class="list-unstyled text-primary lead mb-3">
<li>{% LocationFeaturesList.ToString().Replace("|","</li><li>") %}</li>
</ul>
{% } #%}
/* CSS cache busting */
<link href="~/CMSPages/GetResource.ashx?stylesheetname=<CODE_NAME>&vid={% GlobalObjects.CssStylesheets.<CODE_NAME>.StylesheetVersionGUID #%}" type="text/css" rel="stylesheet"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment