最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

rust - Reusing form for both creating and editing an entity in Askama - Stack Overflow

matteradmin8PV0评论

Using Askama, I'm trying to create a form template that can be included in both the creation and editing template for an entity (e.g. a blog post). In the former the form would start out empty and in the latter it would be filled with values fetched from the database.

Here's the template I got so far (post is a struct passed into the template, which is None in the case of the creation flow):

{% let action -%}
{% let method -%}
{% let title -%}
{% let content -%}
{% let author -%}
{% if let Some(post) = post -%}
  {% let action = format!("/posts/{}", post.id) %}
  {% let method = "data-hx-put" %}
  {% let title = post.title.as_ref() -%}
  {% let content = post.content.as_ref() -%}
  {% let author = post.author.as_ref() -%}
{% else -%}
  {% let action = "/posts".to_string() %}
  {% let method = "data-hx-post" %}
  {% let title = "" -%}
  {% let content = "" -%}
  {% let author = "" -%}
{% endif -%}

<form {{method}}="{{ action }}">
    <fieldset>
        <div class="form-group">
            <label for="title">Title</label>
            <input class="form-control" name="title" value="{{ title }}" />
        </div>
        <div class="form-group">
            <label for="content">Content</label>
            <textarea class="form-control" name="content">
                   {{- content -}}
            </textarea>
        </div>
        <div class="form-group">
            <label for="author">Author</label>
            <input class="form-control" name="author" value="{{ author }}" />
        </div>
        <input class=" btn btn-primary" type="submit" />
    </fieldset>
</form>

Writing it this way is very verbose and thus tedious. Is there a better way in Askama to write this?

Post a comment

comment list (0)

  1. No comments so far