tipsy / j2html

Java to HTML generator. Enjoy typesafe HTML generation.

Home Page:https://j2html.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Tag should have a method to add an Attribute (not name and value to build one)

kicktipp opened this issue · comments

   /**
    * Adds the specified attribute. If the Tag previously contained an attribute with the same name, the old attribute is replaced by the specified attribute.
    *
    * @param attribute the attribute
    * @return itself for easy chaining
    */
   public T attr(Attribute attribute) {
       Iterator<Attribute> iterator = attributes.iterator();
       String name = attribute.getName();
       if (name != null) {
           // name == null is allowed, but those Attributes are not rendered. So we add them anyway.
           while (iterator.hasNext()) {
               Attribute existingAttribute = iterator.next();
               if (existingAttribute.getName().equals(name)) {
                   iterator.remove();
               }
           }
       }
       attributes.add(attribute);
       return (T) this;
   }

This is important for dynamic Attributes which get their data from the model when rendering.

    public class DynamicHrefAttribute extends Attribute  {
        public DesktopHrefAttribute () {
            super("href");
        }

        @Override
        public void renderModel ( Appendable writer, Object model ) throws IOException {
            writer.append(" ");
            writer.append(getName());
            writer.append("=\"");
            writer.append(getUrl(model));
            writer.append("\"");
        }

        public abstract String getUrl ( Object model );
    }

PR is following in a few minutes

commented

Thanks, merged.