Reputation: 1341
Is it possible to use a Sitecore field inside javascript? For instance the google analytics script:
How can the Web Property ID ('UA-XXXX-Y') be filled in by a Sitecore field instead of being hardcoded.
<!-- Google Analytics -->
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
Upvotes: 0
Views: 1873
Reputation:
Here is an option to recreate the script in the code behind (.cs file):
var script = String.Format("<script>(function (i, s, o, g, r, a, m) {{i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {{(i[r].q = i[r].q || []).push(arguments)}}, i[r].l = 1 * new Date(); a = s.createElement(o),m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)}})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');ga('create', '{0}', 'auto');ga('send', 'pageview');</script>", Sitecore.Context.Item.Fields["Google Analytics ID Field"]
The string.format creates a string with the script. {0} will be filled with the first parameter after the script. In this case it will fetch the value of the 'Google Analytics ID Field' of the current item and insert it into the script.
Upvotes: 0
Reputation: 65
You can also use scriplets in the front end. Just create a variable above the function that is set to your sitecore item's field that you need passed in:
<!-- Google Analytics -->
<script>
var webpropID = "<%=webProperty.ID %>";
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', webpropID , 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
Upvotes: 1
Reputation: 4410
If you have an item with the code (UA-XXX-Y) in Sitecore somewhere, you could use something like Sitecore.Context.Database.GetItem(*Guid to item holding the code goes here*)
to access the item.
If you then use something like ScriptManager.RegisterStartupScript
you can add the JavaScript code from codebehind. You'll need to havea ll the text of the script built in a StringBuilder or something similar though
Upvotes: 2