Skip to main content

Template xojs

Cấu trúc của cơ bản của xojs là ta chỉ cần viết html là đủ

<div>Đây là element</div>

Nâng cao hơn 1 chút ta có thể sử dụng các biến được tạo từ config.ts như sau

Xem chi tiết config tại đây: Element Config

  1. foo.config.ts
import { ElementsEntity } from "@xobuilder/entities";

export const config: Omit<ElementsEntity.Element, 'id' | 'template'> = {
type: "element",
label: "Heading",
labelSync: 'element.settings.title',
icon: "AccessibilityMajor",
categories: ["basic"],
schema: [
{
id: "title",
type: "text",
label: "Heading text1",
default: "This is your heading text",
}
],
};

  1. foo.xojs
<div>
<h2>${element.settings.title}</h2>
</div>

<script design-mode> là khu vực giúp ta có thể sử dụng tối đa cú pháp javascript và các hàm hỗ trợ giúp việc render element dễ dàng hơn khi thao tác với dữ liệu

Xem thêm các hàm hỗ trợ: Script Design Mode

<script design-mode>
const settings = {
...global.settings,
...page.settings,
...element.settings
};

function renderText() {
return `<div>Render thử 1 thứ gì đó</div>`
}
</script>

<div>
<h2>${settings.title}</h2>
${renderText()}
</div>

Sử dụng biến đặc biệt $children, biến này để sử dụng cho element thuộc loại wrapper

<div class="container">
$children
</div>

Cách viết code liquid

Chú ý trường hợp nhúng 1 biến vào liquid mà có thể thay đổi dữ liệu liquid (Tức là cần compile)

  1. foo.config.ts
import { ElementsEntity } from "@xobuilder/entities";

export const config: Omit<ElementsEntity.Element, 'id' | 'template'> = {
type: "element",
label: "Heading",
labelSync: 'element.settings.title',
icon: "AccessibilityMajor",
categories: ["basic"],
schema: [
{
id: "title",
type: "text",
label: "Heading text1",
default: "This is your heading text",
},
{
// Đối với những dữ liệu liên quan tới việc cần compile lại code liquid thì giá trị của id phải có $ đằng trước
id: "$collection",
type: "collection",
label: "Collection",
default: "best-seller",
},
{
id: "titleColor",
type: "text",
label: "Title color",
default: "red",
},
],
};

  1. foo.xojs
<script design-mode>
const { title, $collection, titleColor } = elements.settings;
</script>

<div>
<h2>${title}</h2>
{% for product in collections[${#$collection#}].products %}
<div style="color: ${titleColor}">{{ product.title }}</div>
{% endfor %}
</div>

Ở phía trên ta thấy $collection đang tác động và làm ảnh hưởng tới dữ liệu liquid Vì thế nên ta cần phải sử dụng cú pháp sau ${#element.settings.$collection#}, chú ý dấu #

Tối ưu hoá render cho editor

Đối với template có chứa html quá lớn ta có thể phân vùng để render tốt hơn với <xo-parser> và các html ngoài xo-parser sẽ không render lại Chú ý chỉ phục vụ việc render nhanh hơn trên editor đối với template có kích thước quá lớn Và ta có thể phân nhiều vùng xo-parser trong 1 element

<xo-parser>
<div>
<h2>${element.settings.title}</h2>
</div>
</xo-parser>
<div>
Dưới này có thể là template tĩnh quá lớn
</div>