Skip to content

Instantly share code, notes, and snippets.

@DavidForster
Last active December 22, 2015 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidForster/6455674 to your computer and use it in GitHub Desktop.
Save DavidForster/6455674 to your computer and use it in GitHub Desktop.
Example SDL Tridion .Net templates to create a JSON file as a package item and then publish it as a binary variant
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;
namespace Test.JsonTemplates
{
class CreateTestData : ITemplate
{
public void Transform(Engine engine, Package package)
{
string JSON = "{\"h3title\":\"09/04/2013\"}";
var jsonItem = package.CreateStringItem(ContentType.Unknown, JSON);
jsonItem.Properties.Add(Item.ItemPropertyFileName, "test");
jsonItem.Properties.Add(Item.ItemPropertyFileNameExtension, "json");
package.PushItem("test.json", jsonItem);
}
}
}
using System;
using Tridion.ContentManager;
using Tridion.ContentManager.CommunicationManagement;
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;
namespace Test.JsonTemplates
{
[TcmTemplateTitle("Publish JSON package items as Variants")]
public class PublishJsonFiles : ITemplate
{
public void Transform(Engine engine, Package package)
{
//Get all items of unknown type from the package
var items = package.GetAllByType(ContentType.Unknown);
//Remove all items that are NOT JSON files
foreach (var item in items)
{
if (!item.Properties[Item.ItemPropertyFileNameExtension].Equals("json", StringComparison.OrdinalIgnoreCase))
{
items.Remove(item);
}
}
//Check the package values for an optional structure group ID to publish to
var optionalStructureGroupId = package.GetValue("jsonStructureGroup");
StructureGroup jsonStructureGroup = null;
//Go get the structure group from Tridion if an Id has been specified
if (!String.IsNullOrWhiteSpace(optionalStructureGroupId))
{
var structureGroupTcmUri = new TcmUri(
Convert.ToInt32(optionalStructureGroupId),
ItemType.StructureGroup,
engine.PublishingContext.RenderedItem.ResolvedItem.Item.Id.PublicationId);
jsonStructureGroup = (StructureGroup)engine.GetObject(structureGroupTcmUri);
}
//Publish out the JSON files
foreach (var item in items)
{
var filename = item.Properties[Item.ItemPropertyFileName] + "." + item.Properties[Item.ItemPropertyFileNameExtension];
//If no structure group has been specified, publish to the default images directory configured for the publication
if (jsonStructureGroup == null)
{
engine.PublishingContext.RenderedItem.AddBinary(
item.GetAsStream(),
filename,
filename,
null,
"application/json");
}
else
{
engine.PublishingContext.RenderedItem.AddBinary(
item.GetAsStream(),
filename,
jsonStructureGroup,
filename,
null,
"application/json");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment