Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Alex 22 posts 105 karma points
    Jun 22, 2017 @ 20:45
    Alex
    0

    How to insert javascript in footer from any part of template?

    Hello, I am coming from Orchard CMS and the nice feature was adding reference to Javascript from any place of template to footer. In the code it looked like this (and I can insert it in any part of the code, but it will be rendered in the footer):

        @using (Script.Foot())
    {
        < script id="dsq-count-scr" src="//yaplex.disqus.com/count.js" async></ script>
    }
    

    Is it something similar for Umbraco, I am trying to find, but can'f find anything similar. The only way is to use @section, but that is not so convinient as the code above.

  • Nicholas Westby 2054 posts 7103 karma points c-trib
    Jun 22, 2017 @ 21:00
    Nicholas Westby
    0

    You can create a static function that you can call from anywhere. Then in your Razor views, you can call that function to indicate the JavaScript path you want to be rendered in the footer. The Razor layout that renders the footer can then render those scripts.

    The best place to store the JavaScript to be rendered would be in HttpContext.Current.Items (only stores items for the current HTTP request).

    This should work, as partial views and views should be rendered before the layouts (i.e., rendering should happen with deepest items first).

  • Alex 22 posts 105 karma points
    Jun 27, 2017 @ 12:54
    Alex
    0

    Thanks Nicholas, I was hoping there is a out of the box solution :(

  • Kevin Jump 2327 posts 14813 karma points MVP 8x c-trib
    Jun 27, 2017 @ 14:31
    Kevin Jump
    101

    Hi Alex,

    you can achieve something similar with the ClientDependencyFramework. which is included as part of umbraco

    Using the CDF you can define a place in your template where you want javascript to render

    @Html.RenderJsHere() 
    

    then in subsequent templates or partials, you can require the JS file

    @Html.RequiresJS("//some.path/to/jsfile.js") 
    

    and when the page is built it will be put in the right place the key is to add @using ClientDependency.Core.Mvc; to the top of the template / partials where you need it. (you can update the web.config in the views folder - but that is a bit more of an upgrade pain)

    some examples of this here:

  • Alex 22 posts 105 karma points
    Jun 27, 2017 @ 14:51
    Alex
    0

    Thanks Kevin, that is exactly what I am looking for.

Please Sign in or register to post replies

Write your reply to:

Draft