|
| 1 | +--- |
| 2 | +outline: deep |
| 3 | +--- |
| 4 | + |
| 5 | +# Herb Java Bindings |
| 6 | + |
| 7 | +Herb provides official Java bindings through JNI (Java Native Interface) to the C library, allowing you to parse HTML+ERB in Java projects with native performance. |
| 8 | + |
| 9 | +> [!TIP] More Language Bindings |
| 10 | +> Herb also has bindings for: |
| 11 | +> - [Ruby](/bindings/ruby/) |
| 12 | +> - [JavaScript/Node.js](/bindings/javascript/) |
| 13 | +> - [Rust](/bindings/rust/) |
| 14 | +
|
| 15 | +## Installation |
| 16 | + |
| 17 | +### Prerequisites |
| 18 | + |
| 19 | +Ensure you have Java installed: |
| 20 | + |
| 21 | +:::code-group |
| 22 | +```shell |
| 23 | +java -version |
| 24 | +``` |
| 25 | +::: |
| 26 | + |
| 27 | +### Build from Source |
| 28 | + |
| 29 | +Clone the repository and build the Java bindings: |
| 30 | + |
| 31 | +:::code-group |
| 32 | +```shell |
| 33 | +git clone https://github.com/your-org/herb.git |
| 34 | +cd herb/java |
| 35 | +make templates |
| 36 | +make jni |
| 37 | +make java |
| 38 | +``` |
| 39 | +::: |
| 40 | + |
| 41 | +This creates the native library (`libherb_jni.dylib` on macOS, `.so` on Linux). |
| 42 | + |
| 43 | +### Setting Up Your Project |
| 44 | + |
| 45 | +Add the compiled classes to your classpath and ensure the native library is in your `java.library.path`. |
| 46 | + |
| 47 | +## Getting Started |
| 48 | + |
| 49 | +### Basic Example |
| 50 | + |
| 51 | +Here's a simple example of parsing HTML+ERB: |
| 52 | + |
| 53 | +:::code-group |
| 54 | +```java |
| 55 | +import org.herb.Herb; |
| 56 | +import org.herb.ParseResult; |
| 57 | + |
| 58 | +public class Example { |
| 59 | + public static void main(String[] args) { |
| 60 | + String source = "<h1><%= user.name %></h1>"; |
| 61 | + |
| 62 | + ParseResult result = Herb.parse(source); |
| 63 | + |
| 64 | + if (result.getValue() != null) { |
| 65 | + System.out.println(result.getValue().treeInspect()); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
| 70 | +::: |
| 71 | + |
| 72 | +### Lexing Example |
| 73 | + |
| 74 | +You can also tokenize HTML+ERB source: |
| 75 | + |
| 76 | +:::code-group |
| 77 | +```java |
| 78 | +import org.herb.Herb; |
| 79 | +import org.herb.LexResult; |
| 80 | +import org.herb.Token; |
| 81 | + |
| 82 | +public class LexExample { |
| 83 | + public static void main(String[] args) { |
| 84 | + String source = "<h1><%= user.name %></h1>"; |
| 85 | + |
| 86 | + LexResult result = Herb.lex(source); |
| 87 | + |
| 88 | + for (Token token : result.getTokens()) { |
| 89 | + System.out.println(token.inspect()); |
| 90 | + } |
| 91 | + } |
| 92 | +} |
| 93 | +``` |
| 94 | +::: |
0 commit comments