Creating Functions in C# Code Fragments aka C# TBB

Most of us are comfortable with writing  just a few bunch of code lines in a C# TBB. Ever thought of writing functions in a C# TBB ? And wonder how to call these functions…

Let’s get Movin’…

  1. Use the syntax <%!  %>  for defining functions inside the TBB.
  2. You can define any number of functions as you like and call them.
<%@ Import Namespace="Tridion.ContentManager.ContentManagement.Fields"%>

string test ="Hello_From_C# TBB";
package.PushItem("Hello_C# TBB", package.CreateStringItem(ContentType.Text,test));

PushWelcomeMessageToPackage();
ProcessComponent();

<%! 

private void PushWelcomeMessageToPackage()
 {
   package.PushItem("Hello_From_Function_1", package.CreateStringItem(ContentType.Text,                                                                     "Got It"));
 }
  
private void ProcessComponent()
{
   Item compItem= package.GetByType(ContentType.Component);
   Component component = engine.GetObject(compItem.GetAsSource().GetValue("ID")) 
                         as Component;
ItemFields componentFields = new ItemFields(component.Content, component.Schema);

if (componentFields.Contains("BrandTitle"))
    { 
         TextField title= componentFields["BrandTitle"] as TextField; 
         package.PushItem("BrandTitle", package.CreateStringItem(ContentType.Text, 
                                                                 title.Value));
    }
}

%>

Run the Above TBB with any component and below are the results:

Output

Hope you enjoyed this post. Comments and Suggestions are welcome.


2 thoughts on “Creating Functions in C# Code Fragments aka C# TBB

  1. Thanks for sharing, but what would be the advantage of the C# TBB with C# Code fragment like this then the one that need to be compiled

    Like

    1. So you are asking about advantages of a C#TBB over the Compiled one ( .NET Assemblies etc..).

      I strongly recommend you to read this blog post: http://www.albertteboekhorst.com/tridion_introduction/tridion-net-templating-yea-or-nay/ by Albert te Boekhorst. This post gives an excellent insight into the Pros and Cons of .NET Templating and very clearly outlines the reasons to prefer .NET Templating (over TBBs of course).

      And thank you for your time to read my article and improving it further through questions.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s