在Grails中将CSS编译为HTML中的内联样式?

con*_*ile 7 html grails spring grails-plugin grails-2.0

我想为html电子邮件生成GSP模板.为了支持更多邮件客户端,建议在html样式元素中使用内联css.

以下是对该主题的讨论:将"编译"为HTML作为内联样式

是否有Grails插件,我可以指定某些GSP文件,CSS应该编译为内联?

如果没有插件,我如何指定应该内联编译css的GSP文件?

这是一个例子.我使用Grails邮件插件发送的html邮件有以下GSP模板.

/mail/signup_mail.gsp
/mail/welcome.gsp
/mail/newsletter.gsp
Run Code Online (Sandbox Code Playgroud)

每个GSP文件都包含一个style.css文件.这应该是内联编译的.

emi*_*lan -3

您可以将以下 Java 代码放入您的 grails 应用程序中。

    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} \n p{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.
}
}
Run Code Online (Sandbox Code Playgroud)

  • @emilan 请提供 mote 的详细信息,它是如何使用的? (2认同)