Skip to content

Component

Tong Lam edited this page Mar 24, 2024 · 3 revisions

In our project, we will organize frontend codes using components to maximize code reusability.

Structure

/templates/component/[component category]
  • Basic components such as card, table, and list will be placed directly under the /component folder.
  • For components specific to a certain category, such as layout, you can create a subfolder under the /component folder with the corresponding category name, like /component/layout/.

Template Macro

One effective method to organize components is by using Jinja2 Template macros.

Basic Macro Example

You can define a macro similar to how you define a Python function.

# see /app/templates/components/layout/footer.html

{% macro footer_menu_item(title, url, icon_class, button_class = "btn
btn-outline-dark border-0 m-1") -%}

<a
  data-mdb-ripple-init
  class="{{ button_class }}"
  href="{{ url }}"
  role="button"
  data-mdb-ripple-init
  data-mdb-tooltip-init
  data-mdb-placement="top"
  title="{{ title }}"
>
  <i class="{{ icon_class }}"></i>
</a>

{%- endmacro %}

Use in the same html

If you want to use a macro defined in the same file, simply use {{ macro }} to call it.

# see /app/templates/components/layout/footer.html

{% macro render_footer() -%}

<footer>
  <div
    class="navbar navbar-light bg-body-tertiary d-sm-flex d-md-none fixed-bottom"
  >
    <!-- home -->
    {{ footer_menu_item("Home", "/", "fa-solid fa-house fa-xl") }}

    <!-- popular -->
    {{ footer_menu_item("Popular", "{{ url_for('popular.popular') }}", "fa-solid
    fa-bolt fa-xl") }}

    <!-- create -->
    {{ footer_menu_item("Create", "{{ url_for('post.create') }}", "fa-solid
    fa-plus fa-xl", "btn btn-danger rounded m-1 px-3") }}

    <!-- community -->
    {{ footer_menu_item("Community", "{{ url_for('community.community') }}",
    "fa-solid fa-users fa-xl") }}

    <!-- search -->
    {{ footer_menu_item("Search", "{{ url_for('search.search') }}", "fa-solid
    fa-magnifying-glass fa-xl") }}
  </div>
</footer>

{%- endmacro %}

Use in the different html

If you want to use a macro defined in a different file, you need to import the macro HTML first, and then you can call it.

# see /app/templates/components/layout.html

{% import './components/layout/footer.html' as footer %} 

{{ footer.render_footer() }}

Component in the Project

Clone this wiki locally