An open API service indexing awesome lists of open source software.

https://github.com/xvrh/html_template


https://github.com/xvrh/html_template

Last synced: 3 months ago
JSON representation

Awesome Lists containing this project

README

          

# html_template

A server-side HTML template engine in Dart.

![intellij-screenshot](https://raw.githubusercontent.com/xvrh/html_template/master/doc/screenshot.png)

### Features

- Auto-completion and static analysis in the template.
- Classical control-flow constructs: `*if`, `*for`, `*switch`
- Conditionally add CSS classes (`[class.my-class]="$condition"`) and HTML attributes (`[disabled]="$condition"`)
- Automatically escapes the variables
- Syntax highlighting (in IntelliJ-based IDE)

### Example

#### Write the template code

Declare a private `void` function tagged with a `@template` attribute:

```dart
import 'package:html_template/html_template.dart';

part 'main.g.dart';

@template
void _productTemplate(Product product) {
'''

$product


''';
}

@template
void _pageTemplate(Product product, {List? scripts}) {
var script = '';
'''


${product.name} - My site



${productTemplate(product)}

''';
}
```

#### Generate the code

- `dart run build_runner watch --delete-conflicting-outputs`

This generates a public function with the same arguments as the original. The generated code looks like:
```dart
// Generated
TrustedHtml productTemplate(Product product) {
var $ = StringBuffer();

$.write(' ');
if (product.icon != null) {
$.write('');
}
$.write('\n ');
$.write('

');
$.write(TrustedHtml.escape(product));
$.write('

');
$.write('\n ');

return TrustedHtml($.toString());
}

//...
```
See the real generated code [here](example/lib/main.g.dart)

#### Use the template

Call the generated public methods to build the HTML page from your data.
```dart
void main() {
router.get('/products/', (request) async {
var product = await database.findProduct(params(request, 'id'));

// Create the html for the response from the Product of your database
var html = pageTemplate(product);

return Response.ok(html, headers: {'content-type': 'text/html'});
});
}
```

### Conditions
```dart
@template
void _conditionExample({required bool someCondition}) async {
'''

Condition on a tag












''';
}
```

### Loop
To repeat an HTML element, use the attribute: `*for="$item in $iterable"`.

```dart
@template
void _simpleLoop(List menu) {
MenuItem? item;
'''



  • ${item.title}


''';
}
```

Notice that we have to define the `item` variable outside of the string literal.
This is a bit unfortunate but string literals don't allow to define a variable inside them.

Alternatively, we can write the loop in Dart arround the string literals:
```dart
@template
void _alternativeLoop(List menu) {
'

    ';
    for (var item in menu) {
    '
  • ${item.title}
  • ';
    }
    '
';
}
```

### Switch
```dart
@template
void _switchExample(Season season) {
'''


Hot
Cold
Pleasant


''';
}
```

### CSS Classes
```dart
@template
void _cssClassesExample(List data, {bool showMenu = false}) {
// Add classes based on condition
'

  • Actif
  • ';

    // We can pass a Map to the [classes] attribute
    var myClasses = {'enabled': showMenu};
    '';
    }
    ```

    ### Dart code
    You can use normal Dart code around the string literals to do complex things in your template.
    You can have has many strings literal as you want.

    ```dart
    @template
    void _movieTemplate() async {
    '

    My movies

    ';

    var page = await fetchPage();
    if (!page.isLoggedIn) {
    '

    Log in

    ';
    } else {
    '
      ';
      for (var movie in page.myMovies) {
      '
    • $movie
    • ';
      }
      '
    ';
    }
    'Footer';
    }
    ```

    ### Nested template & master layout
    Include another template by calling the generated function in a string interpolation:

    ```dart
    @template
    void _myTemplate() {
    '''

    Images


    ${img('landscape.png')}
    ''';
    }

    @template
    void _img(String url) {
    '';
    }
    ```

    ### Others
    - Use `xx` tag if you want to output some text without the html element wrapper.

    - Use this comment in your dart file to workaround linter warnings

    // ignore_for_file: unnecessary_statements