Search code examples
grailsgsp

Grails: How to add css styles to page dynamicly?


I write plugin, which has taglib like this:

class MyTagLib {

    static namespace = "my"

    Closure someWidget = { attrs ->
       // Need somehow add styles to page
       // ...
    }
}

I use asset-pipeline plugin and can't find any way to add stylesheets dynamicly (into head tag).

Base gsp layout of application (not my plugin):

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <g:layoutHead/>
    <title><g:layoutTitle/></title>
</head>
<body>
    <g:layoutBody/>
    <asset:deferredScripts/>
</body>
</html>

I need something like that in taglib:

g.putItIntoHead(asset.stylesheet(src: 'assets/my.css'))

Solution

  • What you are looking for is a tag that injects a javascript code that does just that.

    class MyTagLib {
    
        static namespace = "my"
    
        Closure putItIntoHead= { attrs ->
           out << " var head = document.head "; 
           out << " var link = document.createElement('link')";
    
           out << " link.type = 'text/css'";
           out << " link.rel = 'stylesheet'";
           out << " link.href = '{url}'";
    
           out << " head.appendChild(link)";
        }
    }
    

    You can also do it using jquery, ( check this question for more)

    And You don't necessarily have add it to the head.