Developer forum

Forum » Development » Get Template parent/owner template

Get Template parent/owner template


Reply
Is it possible to get a loop templates parent/owner template from the TemplateV2 class?
 
Something like this:
Template myLoopTemplate = myTemplate.GetLoop(“MyLoop”);
If (myLoopTemplate.ParentTemplate.TagExists(“MyTag”))
       //Found!

Replies

 
Reply
Hi there,

I am not 100% sure, but I don't think there's a way to do it directly. The V2 Template class has a Parent property but it's internal and thus not directly accessible.

I tried a few ways including an extension method on Template that returns a derrived type which has a ParentTemplate property . However, I ran into casting issues that *may* be solved by .NET 4 co- and contravariance. However, due to some other issues running DW under .NET 4 on my machine I couldn't test it out.

Another way is to use reflection in combination with extension methods. CAUTION: following code should probably be considered as "interesting, but I don't want to use it". Using reflection can be slow and can lead to security issues. Also, DW may decide to rename or remove the Parent property or they may decide to make it public (which, IMO is probably a good idea and would solve your problem right away) which would completely break your application.

That all said, add the following to a class file:

namespace Dynamicweb.Samples.Lib
{
public static class TemplateExtensions
{
public static Dynamicweb.Templatev2.Template ParentTemplate(this Dynamicweb.Templatev2.Template template)
{
Type myType = typeof(Dynamicweb.Templatev2.Template);
PropertyInfo field = myType.GetProperty("Parent"BindingFlags.Instance | BindingFlags.NonPublic);
return (Dynamicweb.Templatev2.Template)field.GetValue(template, null);
}
}
}
You can then use the extension method as follows:

using Dynamicweb.Samples.Lib;
... Dynamicweb.Templatev2.Template childTemplate = template.GetLoop("MyLoop");
if (childTemplate.ParentTemplate().TagExists("ParentTag"))
{
template.SetTag("ParentTag""Some Value");
}
The extension method ParentTemplate retuns the Parent property of your child template using reflection. You can then use it to call TagExists as you normally would.

Again: use with caution. I tested it, and it seems t work fine, but don't sue me if it kills your dog or causes you to lose your job ;-)

Cheers,

Imar



 
Reply
Hi Imar,
 
Thanks for your reply. As you wrote the best way to solve this is Dynamicweb making the Parent property public.
 
Att.: Dynamicweb,
 
Is it possible to make the Parent property on the TemplateV2.Templete public?  
 
Jeppe Eriksson Agger Dynamicweb Employee
Jeppe Eriksson Agger
Reply
I don't see an issue with making the Parent property public right off the bat, but it's something we need to discuss in the dev team.

 

You must be logged in to post in the forum