Reputation: 17508
The following piece of code executes as expected when placed in a user control or ASPX page.
<script type="text/javascript">
(function() {
if (someCondition) {
if (<%=MyObject.IsActiveSession.ToString().ToLower() %>) {
<% If (MyObject.IsLoggedIn) Then %>
// Do some fancy stuff
<% End If %>
}
}
})();
</script>
It renders as you would expect when the page executes.
Is there any way I can inject this code in the page dynamically and have it execute?
I tried using a Literal Web Control and surprise surprise, it output the code literally :)
Upvotes: 0
Views: 353
Reputation: 19217
There aren't much friendly Template Engines available for .NET atleast for the community. I ran into the same trouble last year where I had to keep some portion of my codes maintained by the clients as they wanted to format their own way of text formatting.
The easiest way I found without getting into any 3rd party libraries is using the power of ASPX
rendering engine as your template code, but in a manageable way.
Create an ASPX
page for your template for instance ~\Templates\LoggedInBlock.aspx
and as content:
<script type="text/javascript">
(function() {
if (someCondition) {
if (<%=MyObject.IsActiveSession.ToString().ToLower() %>) {
<% If (MyObject.IsLoggedIn) Then %>
// Do some fancy stuff
<% End If %>
}
}
})();
</script>
Now create a template renderer generic handler, for instance ~\TemplateRenderer.ashx
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Web
Namespace TestApp1
Public Class TemplateRenderer
Implements IHttpHandler
Private Function GetContent(context As HttpContext, tempateName As String) As String
Using textWriter = New StringWriter()
context.Server.Execute(String.Format("~/Templates/{0}", tempateName), textWriter)
Return textWriter.ToString()
End Using
End Function
Public Sub ProcessRequest(context As HttpContext)
context.Response.Write(GetContent(context, context.Request.QueryString("template")))
End Sub
Public ReadOnly Property IsReusable() As Boolean
Get
Return False
End Get
End Property
End Class
End Namespace
Now from where you want your dynamic code block to append as it just another small piece of ASPX
page:
Protected Sub Page_Load(sender As Object, e As EventArgs)
Dim templateName = "LoggedInBlock.aspx"
Using textWriter = New StringWriter()
Server.Execute(String.Format("~/TemplateRenderer.ashx?template={0}", templateName), textWriter)
dynamicCodeInjectPanel.InnerHtml = textWriter.ToString()
End Using
End Sub
Courtesy: http://converter.telerik.com/ used to convert from C# to VB code.
Upvotes: 1
Reputation: 30152
Not in any manner I would consider very clean, although I believe it is possible using dynamic compilation in the codedom
See: http://www.codeproject.com/KB/cs/smarttemplateengine.aspx
Upvotes: 0