4

Using GWT 2.1, I am trying to create a CSS file that contains numerous constants and common styles. I would like to use the ui:style tag to include it in the UiBinder template:

<ui:UiBinder
  xmlns:ui='urn:ui:com.google.gwt.uibinder'
  xmlns:g='urn:import:com.google.gwt.user.client.ui'

  <ui:style field="css" src="constants.css" />
</ui:UiBinder>

I can easily utilize the styles for elements:

<g:FlowPanel styleName="{css.panel}">...</g:FlowPanel>

But attempting to use the constants in another Style block fails:

<ui:Style>
  .templateSpecificStyle {
      background-color: {css.royalBlue};
      padding: 1em;
  }
</ui:Style>

Oddly I do not receive a compile error. The obfuscated CSS class is created; however, the content is empty. Is there any way to access these CSS constants within another Style block? Is it possible using the older ResourceBundle / CssResource pattern?

schrierc
  • 143
  • 1
  • 9

2 Answers2

7

After re-reading https://stackoverflow.com/questions/3533211/need-app-wide-css-constants-in-gwt/4143017#4143017 I see that the constants work if you add the template specific style within the style block:

<ui:Style src="constants.css">
  .templateSpecificStyle {
      background-color: royalBlue;
      padding: 1em;
  }
</ui:Style>

This is perfect for my needs.

Community
  • 1
  • 1
schrierc
  • 143
  • 1
  • 9
4

It may be in your best interest to define these constants in some class, then use runtime substitution to include this constant in each CSS resource you intend to use.

CSSConstants.java

package com.foo.client;
public final class CSSConstants {
    public static final String ROYAL_BLUE = "#4169E1";
}

Style block in UiBinder template

<ui:style>
  @eval royalBlue com.foo.client.ROYAL_BLUE
  .templateSpecificStyle {
    background-color: royalBlue
  }
</ui:style>

Note that even the name of the technique is "runtime substitution", the GWT compiler will replace royalBlue with a string literal because the value of royalBlue can be evaluated at compile time.

For more cool stuff that you can do in CSS resources, take a look at http://code.google.com/webtoolkit/doc/latest/DevGuideClientBundle.html#CssResource

Wesley
  • 10,652
  • 4
  • 37
  • 52
  • It seems really verbose, and somewhat ugly, to @eval each of the constants I wish to reference in each UiBinder template. The constants.css also contains a few useful styles. I am really hoping there is a cleaner way. The is an incredibly nice feature because it automatically generates the interfaces. – schrierc Nov 12 '10 at 22:32
  • I agree - a lot of GWT stuff can get quite verbose at times. An alternative approach is to extend the `CssResource` interface so that you can expose the constants that way. This would save you from creating `CSSConstants.java`. However, you'd still need an `@eval` to get those styles where they need to go. – Wesley Nov 12 '10 at 23:33