Compile CSS to HTML as an inline style in Grails?

I want to generate GSP templates for html emails. To support more email clients, it is recommended to use inline css in html style elements.

The following is a discussion of this topic: Compile CSS to HTML as Inline Styles

Is there a Grails plugin where I can specify some GSP files for which CSS should be compiled as inline?

If the plugin is missing, how can I specify the GSP files for which css should run inline?

Here is an example. I have the following GSP templates for my html emails that I send using the Grails plugin .

/mail/signup_mail.gsp /mail/welcome.gsp /mail/newsletter.gsp 

Each GSP file contains a style.css file. This must be compiled.

+7
spring html grails grails-plugin
source share
2 answers

In a grails application, you can put the following Java code.

  import java.io.IOException; import java.util.StringTokenizer; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class AutomaticCssInliner { public static void main(String[] args) throws IOException { final String style = "style"; final String html = "<html>" + "<body> <style>" + "body{background:#FFC} \np{background:red}" + "body, p{font-weight:bold} </style>" + "<p>...</p> </body> </html>"; // Document doc = Jsoup.connect("http://mypage.com/inlineme.php").get(); Document doc = Jsoup.parse(html); Elements els = doc.select(style);// to get all the style elements for (Element e : els) { String styleRules = e.getAllElements().get(0).data().replaceAll( "\n", "").trim(), delims = "{}"; StringTokenizer st = new StringTokenizer(styleRules, delims); while (st.countTokens() > 1) { String selector = st.nextToken(), properties = st.nextToken(); Elements selectedElements = doc.select(selector); for (Element selElem : selectedElements) { String oldProperties = selElem.attr(style); selElem.attr(style, oldProperties.length() > 0 ? concatenateProperties( oldProperties, properties) : properties); } } e.remove(); } System.out.println(doc);// now we have the result html without the // styles tags, and the inline css in each // element } private static String concatenateProperties(String oldProp, String newProp) { oldProp = oldProp.trim(); if (!newProp.endsWith(";")) newProp += ";"; return newProp + oldProp; // The existing (old) properties should take precedence. } } 
-2
source share

We do this with the free method in the Mailchimp API. You can also use Premailer.

http://apidocs.mailchimp.com/api/1.2/inlinecss.func.php

http://premailer.dialect.ca/

+1
source share

All Articles