PosthTML에 대한 Laravel Blade에서 영감을 얻은 구성 요소
npm i -D posthtml-component이 posthtml 플러그인은 HTML 템플릿에서 구성 요소를 사용하기위한 HTML 친화적 인 구문을 제공합니다. 블레이드, 반응, vue 또는 이와 유사한 블레이드에 익숙하다면이 플러그인이 영감을 받으므로 구문이 친숙 할 것입니다.
이 플러그인을 사용하여 첫 번째 PosthTML 부트 스트랩 UI를 참조하고 여기에서 스타터 템플릿도 확인하십시오.
| 이름 | 유형 | 기본 | 설명 |
|---|---|---|---|
| 뿌리 | String | './' | 루트 경로 구성 요소를 찾는 곳. |
| 폴더 | String[] | [''] | options.root 에 대한 경로 배열. 루트 또는 정의 된 네임 스페이스. |
| 파일 확장 | String|String[] | 'html' | 찾을 구성 요소 파일 확장. |
| tagprefix | String | 'x-' | 태그 접두사. |
| 꼬리표 | String|Boolean | false | 구성 요소 태그. options.attribute 과 함께 사용하십시오. 부울 만 false . |
| 기인하다 | String | 'src' | 구성 요소 파일로의 경로를 정의하는 데 사용하는 속성. |
| 네임 스페이스 | String[] | [] | 네임 스페이스 루트 경로, 폴백 경로 및 사용자 정의 재정의 경로 배열. |
| 네임 스페이스 분사기 | String | '::' | 태그 이름의 네임 스페이스 분리기. |
| 생산하다 | String | 'yield' | 기본 구성 요소 컨텐츠를 주입하는 태그 이름. |
| 슬롯 | String | 'slot' | 슬롯의 태그 이름 |
| 채우다 | String | 'fill' | 채우기 슬롯의 태그 이름. |
| 슬롯 스피어터 | String | ':' | <slot> 및 <fill> 태그의 이름 분리기. |
| 스택 | String | 'stack' | <stack> 의 태그 이름. |
| 푸시 | String | 'push' | <push> 의 태그 이름. |
| PropsScriptAttribute | String | 'props' | 구성 요소 소품을 검색하려면 <script props> 의 속성. |
| propscontext | String | 'props' | 소품 처리를 위해 스크립트 내부의 객체의 이름. |
| 소품 부사장 | String | 'props' | 속성 이름을 구성 요소 태그에서 JSON으로 정의하려면 이름입니다. |
| 소품 슬롯 | String | 'props' | $slots.slotName.props 통해 슬롯에 전달 된 소품을 검색하는 데 사용됩니다. |
| 구문 분석 | Object | {recognizeSelfClosing: true} | posthtml-parser 에게 옵션을 전달합니다. |
| 표현 | Object | {} | posthtml-expressions 에 옵션을 전달합니다. |
| 플러그인 | Array | [] | PosthTML 플러그인 모든 구문 분석 구성 요소에 적용됩니다. |
| 경기자 | Object | [{tag: options.tagPrefix}] | 태그와 일치하는 데 사용되는 객체 배열. |
| Attsparserrules | Object | {} | 속성에 대한 추가 규칙 Parser 플러그인. |
| 엄격한 | Boolean | true | 예외 던지기 토글. |
| MERGECUSTOMIZER | Function | function | Lodash의 콜백은 options.expressions.locals 병합하기 위해 mergeWith . |
| 유용 | Object | {merge: _.mergeWith, template: _.template} | 유틸리티 메소드는 <script props> 로 전달되었습니다. |
| 요소 | Object | {} | 태그 이름과 기능 수정자가있는 객체 valid-attributes.js . |
| SAFELISTATTRIBUTES | String[] | ['data-*'] | 기본 유효한 속성에 추가 할 속성 이름 배열. |
| Blocklistattributes | String[] | [] | 기본 유효한 속성에서 제거 할 속성 이름 배열. |
구성 요소 생성 :
<!-- src/button.html -->
< button type =" button " class =" btn " >
< yield > </ yield >
</ button >사용 :
<!-- src/index.html -->
< html >
< body >
< x-button type =" submit " class =" btn-primary " > Submit </ x-button >
</ body >
</ html >posthtml init :
// index.js
const posthtml = require ( 'posthtml' )
const components = require ( 'posthtml-component' )
const { readFileSync , writeFileSync } = require ( 'node:fs' )
posthtml ( [
components ( { root : './src' } )
] )
. process ( readFileSync ( 'src/index.html' , 'utf8' ) )
. then ( result => writeFileSync ( 'dist/index.html' , result . html , 'utf8' ) )결과:
<!-- dist/index.html -->
< html >
< body >
< button type =" submit " class =" btn btn-primary " > Submit </ button >
</ body >
</ html > src/button.html 구성 요소에는 type 및 class 속성이 포함되어 있으며 src/index.html 에서 사용할 때 해당 속성을 전달했음을 알 수 있습니다.
그 결과 type 무시되었고 class 병합되었습니다.
기본적으로 class 및 style 속성은 병합되고 다른 모든 속성은 재정의됩니다. 클래스 속성에 대한 override: 을 통해 class 및 style 속성을 무시할 수도 있습니다.
예를 들어:
< x-button override:class =" btn-custom " > Submit </ x-button >
<!-- Output -->
< button type =" button " class =" btn-custom " > Submit </ button > 구성 요소에 전달하는 모든 속성은 구성 요소의 첫 번째 노드 또는 <script props> 를 통해 props 으로 정의되지 않은 경우 에만 구성 attributes 의 첫 번째 노드 또는 이름이 속성이있는 이름으로 추가됩니다 (유효한 속성”이 아닌 경우에만 가능합니다.
플러그인 옵션을 통해 어떤 속성이 유효한 것으로 간주되는지 정의 할 수도 있습니다.
이에 대한 자세한 내용은 속성 섹션에서.
<yield> 태그는 구성 요소로 전달하는 컨텐츠가 주입되는 곳입니다.
플러그인은 posthtml 파서를 자체 폐쇄 태그를 인식하도록 구성하므로 <yield /> 입니다.
간결하게, 우리는 예제에서 자체 폐쇄 태그를 사용합니다.
기본적으로 플러그인은 .html 확장자가있는 구성 요소를 찾습니다. 확장 배열을 fileExtension 옵션에 전달하여이를 변경할 수 있습니다.
배열을 사용하는 경우 이름이 동일한 두 파일이 두 확장자와 일치하면 배열의 첫 번째 확장자와 일치하는 파일이 사용됩니다.
const posthtml = require ( 'posthtml' )
const components = require ( 'posthtml-component' )
posthtml ( [
components ( {
root : './src' , // contains layout.html and layout.md
fileExtension : [ 'html' , 'md' ]
} )
] )
. process ( `<x-layout />` )
. then ( result => console . log ( result . html ) ) // layout.html content 더 많은 예제를 찾을 수있는 docs-src 폴더도 참조하십시오.
이 저장소를 복제하고 npm run build 실행하여 컴파일 할 수 있습니다.
여러 가지 방법으로 구성 요소를 사용할 수 있습니다.
구성 요소를 '포함'으로 사용하려면 태그 및 src 속성 이름을 정의 할 수 있습니다.
이전 버튼 구성 요소 예제를 사용하면 태그와 속성 이름을 정의한 다음 다음과 같이 사용할 수 있습니다.
posthtml init :
// index.js
require ( 'posthtml' ) (
require ( 'posthtml-component' ) ( {
root : './src' ,
tag : 'component' ,
attribute : 'src'
} ) )
. process ( /* ... */ )
. then ( /* ... */ ) 태그 일치에 대한 더 많은 제어가 필요한 경우 options.matcher 통해 매칭 배열 또는 단일 객체를 전달할 수 있습니다.
// index.js
const options = {
root : './src' ,
matcher : [
{ tag : 'a-tag' } ,
{ tag : 'another-one' } ,
{ tag : new RegExp ( `^app-` , 'i' ) } ,
]
} ;
require ( 'posthtml' ) ( require ( 'posthtml-component' ) ( options ) )
. process ( /* ... */ )
. then ( /* ... */ ) posthtml-components 사용하면 x-tag-name 구문을 사용할 때 경로 이름을 지정할 필요가 없습니다.
PosthTML 설정 :
// index.js
const options = {
root : './src' ,
tagPrefix : 'x-'
} ;
require ( 'posthtml' ) ( require ( 'posthtml-component' ) ( options ) )
. process ( /* ... */ )
. then ( /* ... */ )사용:
<!-- src/index.html -->
< html >
< body >
< x-button > Submit </ x-button >
</ body >
</ html > 구성 요소가 하위 폴더에 있으면 dot 사용하여 액세스 할 수 있습니다.
<!-- src/components/forms/button.html -->
< x-forms .button > Submit </ x-forms .button > 구성 요소가 여러 파일이있는 하위 폴더에있는 경우 기본 파일 이름을 쓰지 않으려면 지정하지 않고 index.html 사용할 수 있습니다.
예는 다음과 같습니다.
<!-- src/components/modals/index.html -->
< x-modal .index > Submit </ x-modal .index >
<!-- You may omit "index" part since the file is named "index.html" -->
< x-modal > Submit </ x-modal > options.parserOptions 통해 옵션을 posthtml-parser 로 전달할 수 있습니다.
// index.js
const options = {
root : './src' ,
parserOptions : { decodeEntities : true }
} ;
require ( 'posthtml' ) ( require ( 'posthtml-component' ) ( options ) )
. process ( 'some HTML' , options . parserOptions )
. then ( /* ... */ ) 중요한
플러그인으로 전달하는 parserOptions 은 코드의 process 메소드에 전달되어야합니다. 그렇지 않으면 PosthTML 빌드는 posthtml-parser 기본값을 사용하고 posthtml-component 로 전달한 모든 것을 무시합니다.
플러그인은 기본적으로 자체 폐쇄 태그를 지원하지만 recognizeSelfClosing: true 옵션 객체에서 전달하여 코드의 process 메소드에서도 활성화해야합니다.
// index.js
require ( 'posthtml' ) ( require ( 'posthtml-component' ) ( { root : './src' } ) )
. process ( 'your HTML...' , { recognizeSelfClosing : true } )
. then ( /* ... */ ) process 에 이것을 추가하지 않으면 posthtml은 posthtml-parser 기본값을 사용하며 자체 처리 구성 요소 태그를 지원하지 않습니다. 이로 인해 자체 폐쇄 태그가 출력되지 않은 후 모든 것이 발생합니다.
구성 요소 파일이있는 위치를 완전히 제어 할 수 있습니다. 구성 요소의 기본 루트 경로를 설정하면 여러 폴더를 설정할 수 있습니다.
예를 들어 루트가 ./src 이고 구성 요소가있는 여러 폴더가있는 경우, ./src/components 및 ./src/layouts 와 같이 다음과 같이 플러그인을 설정할 수 있습니다.
// index.js
const options = {
root : './src' ,
folders : [ 'components' , 'layouts' ]
} ;
require ( 'posthtml' ) ( require ( 'posthtml-component' ) ( options ) )
. process ( /* ... */ )
. then ( /* ... */ )네임 스페이스를 사용하면 구성 요소에 대한 최상위 루트 경로를 정의 할 수 있습니다.
구성 요소를 찾을 수없는 경우 폴백 루트가있는 특정 최상위 루트를 정의하고 재정의를위한 사용자 지정 루트를 정의하는 사용자 정의 테마를 처리하는 데 유용 할 수 있습니다.
이렇게하면 다음과 같은 폴더 구조를 만들 수 있습니다.
src (루트 폴더)components (모달, 버튼 등과 같은 구성 요소의 폴더)layouts (기본 레이아웃, 헤더, 바닥 글 등과 같은 레이아웃 구성 요소 폴더)theme-dark (테마 어두운 네임 스페이스 폴더)components (테마 어두운 구성 요소 용 폴더)layouts (어두운 테마를위한 레이아웃 구성 요소 폴더)theme-light (테마 라이트 용 네임 스페이스 폴더)components (라이트 테마의 구성 요소 용 폴더)layouts (어두운 테마를위한 레이아웃 구성 요소 폴더)custom (네임 스페이스 테마를 재정의하는 사용자 정의 폴더)theme-dark (Dark Theme Themer를 재정의하기위한 사용자 정의 폴더)components (테마의 구성 요소 재정의 폴더)layouts (어두운 테마의 레이아웃 구성 요소 재정의 폴더)theme-light (광선 테마 오버라이드를위한 사용자 정의 폴더)components (테마의 구성 요소 재정의 폴더)layouts (어두운 테마의 레이아웃 구성 요소 재정의 폴더)옵션은 다음과 같습니다.
// index.js
const options = {
// Root for component without namespace
root : './src' ,
// Folders is always appended in 'root' or any defined namespace's folders (base, fallback or custom)
folders : [ 'components' , 'layouts' ] ,
namespaces : [ {
// Namespace name will be prepended to tag name (example <x-theme-dark::button>)
name : 'theme-dark' ,
// Root of the namespace
root : './src/theme-dark' ,
// Fallback root when a component is not found in namespace
fallback : './src' ,
// Custom root for overriding, the lookup happens here first
custom : './src/custom/theme-dark'
} , {
// Light theme
name : 'theme-light' ,
root : './src/theme-light' ,
fallback : './src' ,
custom : './src/custom/theme-light'
} , {
/* ... */
} ]
} ;구성 요소 네임 스페이스 사용 :
<!-- src/index.html -->
< html >
< body >
< x-theme-dark : :button >Submit</ theme-dark : :button >
< x-theme-light : :button >Submit</ theme-light : :button >
</ body >
</ html >구성 요소는 사용할 때 컨텐츠로 채워질 수있는 슬롯을 정의 할 수 있습니다.
예를 들어:
<!-- src/modal.html -->
< div class = " modal " >
< div class = " modal-header " >
< slot : header />
</ div >
< div class = " modal-body " >
< slot : body />
</ div >
< div class = " modal-footer " >
< slot : footer />
</ div >
</ div >구성 요소 사용 :
<!-- src/index.html -->
< x-modal >
< fill : header >Header content</ fill : header >
< fill : body >Body content</ fill : body >
< fill : footer >Footer content</ fill : footer >
</ x-modal >결과:
<!-- dist/index.html -->
< div class =" modal " >
< div class =" modal-header " >
Header content
</ div >
< div class =" modal-body " >
Body content
</ div >
< div class =" modal-footer " >
Footer content
</ div >
</ div >기본적으로 슬롯 컨텐츠가 교체되지만 컨텐츠를 선불하거나 추가하거나 슬롯을 채우지 않음으로써 기본 컨텐츠를 유지할 수도 있습니다.
구성 요소에 일부 기본 내용을 추가하십시오.
<!-- src/modal.html -->
< div class = " modal " >
< div class = " modal-header " >
< slot : header >Default header</ slot : header >
</ div >
< div class = " modal-body " >
< slot : body >content</ slot : body >
</ div >
< div class = " modal-footer " >
< slot : footer >Footer</ slot : footer >
</ div >
</ div > <!-- src/index.html -->
< x-modal >
< fill : body prepend>Prepend body</ fill : body >
< fill : footer append>content</ fill : footer >
</ x-modal >결과:
<!-- dist/index.html -->
< div class =" modal " >
< div class =" modal-header " >
Default header
</ div >
< div class =" modal-body " >
Prepend body content
</ div >
< div class =" modal-footer " >
Footer content
</ div >
</ div >다른 구성 요소와 같이 다른 곳에서 렌더링 할 수있는 이름의 스택으로 컨텐츠를 푸시 할 수 있습니다. 이는 구성 요소에 필요한 JavaScript 또는 CSS를 지정하는 데 특히 유용 할 수 있습니다.
먼저 html에 <stack> 태그를 추가하십시오.
<!-- src/index.html -->
<html>
<head>
+ <stack name="styles" />
</head>
<body>
<x-modal>
<fill:header>Header content</fill:header>
<fill:body>Body content</fill:body>
<fill:footer>Footer content</fill:footer>
</x-modal>
+ <stack name="scripts" />
</body>
</html>그런 다음 모달 구성 요소 또는 기타 어린이 구성 요소에서는이 스택으로 컨텐츠를 푸시 할 수 있습니다.
<!-- src/modal.html -->
< div class = " modal " >
< div class = " modal-header " >
< slot : header />
</ div >
< div class = " modal-body " >
< slot : body />
</ div >
< div class = " modal-footer " >
< slot : footer />
</ div >
</ div >
< push name = " styles " >
< link href = " https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css " rel = " stylesheet " >
</ push >
< push name = " scripts " >
< script src = " https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js " ></ script >
</ push >출력은 다음과 같습니다.
<!-- dist/index.html -->
< html >
< head >
< link href =" https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css " rel =" stylesheet " >
</ head >
< body >
< div class =" modal " >
< div class =" modal-header " >
Header content
</ div >
< div class =" modal-body " >
Body content
</ div >
< div class =" modal-footer " >
Footer content
</ div >
</ div >
< script src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js " > </ script >
</ body >
</ html > once 속성을 사용하면 렌더링 사이클 당 컨텐츠를 한 번만 푸시 할 수 있습니다.
예를 들어, 루프 내에서 주어진 구성 요소를 렌더링하는 경우 구성 요소를 처음 렌더링 할 때만 JavaScript와 CSS 만 푸시 할 수 있습니다.
예.
<!-- src/modal.html -->
< div class =" modal " >
<!-- ... -->
</ div >
<!-- The push content will be pushed only once in the stack -->
< push name =" styles " once >
< link href =" https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css " rel =" stylesheet " >
</ push >
< push name =" scripts " once >
< script src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js " > </ script >
</ push > 기본적으로 컨텐츠는 주어진 순서로 스택에 푸시됩니다. 스택의 시작 부분에 컨텐츠를 선출하려면 prepend 속성을 사용할 수 있습니다.
< push name =" scripts " >
<!-- This will be second -->
< script src =" /example.js " > </ script >
</ push >
<!-- Later... -->
< push name =" scripts " prepend >
<!-- This will be first -->
< script src =" /example-2.js " > </ script >
</ push > props HTML 속성의 구성 요소로 전달 될 수 있습니다. 구성 요소에 사용하려면 구성 요소의 <script props> 태그에 정의되어야합니다.
예를 들어:
<!-- src/alert.html -->
< script props >
module . exports = {
title : props . title || 'Default title'
}
</ script >
< div >
{{ title }}
</ div >사용:
< x-alert title =" Hello world! " />출력은 다음과 같습니다.
< div >
Hello world!
</ div > title 속성이 구성 요소로 전달되지 않으면 기본값이 사용됩니다.
< x-my-alert />출력은 다음과 같습니다.
< div >
Default title
</ div > 내부 <script props> 당신은 props 이라는 객체를 통해 전달 된 소품에 액세스 할 수 있습니다.
다음은 다음과 같이 할 수있는 일의 예입니다.
<!-- src/modal.html -->
< script props >
module . exports = {
title : props . title || 'Default title' ,
size : props . size ? `modal- ${ props . size } ` : '' ,
items : Array . isArray ( props . items ) ? props . items . concat ( [ 'first' , 'second' ] ) : [ 'first' , 'second' ]
}
</ script >
< div class =" modal {{ size }} " >
< div class =" modal-header " >
{{ title }}
</ div >
< div class =" modal-body " >
< each loop =" item in items " > < span > {{ item }} </ span > </ each >
</ div >
</ div >사용:
< x-modal
size =" xl "
title =" My modal title "
items =' ["third", "fourth"] '
class =" modal-custom "
/>출력은 다음과 같습니다.
< div class =" modal modal-custom modal-xl " >
< div class =" modal-header " >
My modal title
</ div >
< div class =" modal-body " >
< span > first </ span >
< span > second </ span >
< span > third </ span >
< span > fourth </ span >
</ div >
</ div > 우리가 구성 요소에 전달한 class 속성이 어떻게 내부의 첫 번째 노드의 class 속성 값과 병합되는지 주목하십시오.
콜백 함수를 전달하여 옵션을 통해 정의 된 글로벌 소품과 속성을 병합하는 방식을 변경할 수 있습니다.
기본적으로 모든 소품은 구성 요소로 스코핑되며 중첩 구성 요소에는 사용할 수 없습니다. 그러나 필요에 따라 이것을 변경할 수 있습니다.
구성 요소 생성 :
<!-- src/child.html -->
< script props >
module . exports = {
title : props . title || 'Default title'
}
</ script >
< div >
Prop in child: {{ title }}
</ div > <x-child> 사용하는 <x-parent> 구성 요소를 만듭니다.
<!-- src/parent.html -->
< script props >
module . exports = {
title : props . title || 'Default title'
}
</ script >
< div >
Prop in parent: {{ title }}
< x-child />
</ div >사용 :
< x-parent title =" My title " />출력은 다음과 같습니다.
< div >
Prop in parent: My title
< div >
Prop in child: Default title
</ div >
</ div > 보시다시피, <x-child> 구성 요소의 title <x-parent> 통해 세트가 아닌 기본값을 렌더링합니다.
이것을 변경하려면, 우리는 소품을 중첩 구성 요소로 전달하려면 속성 이름으로 aware: 해야합니다.
< x-parent aware:title =" My title " />이제 출력은 다음과 같습니다.
< div >
Prop in parent: My title
< div >
Prop in child: My title
</ div >
</ div > 속성을 구성 요소에 전달할 수 있으며 구성 요소의 첫 번째 노드 또는 attributes 이라는 속성이있는 노드에 추가됩니다.
vue.js에 익숙하다면 소위 러프 속성과 동일합니다. 또는 Laravel Blade를 사용하면 구성 요소 부족입니다.
기본적으로 class 와 style 기존 class 및 style 속성과 병합됩니다. 다른 모든 속성은 기본적으로 재정의됩니다.
prop 으로 정의 된 속성을 전달하면 구성 요소의 노드에 추가되지 않습니다.
예는 다음과 같습니다.
<!-- src/button.html -->
< script props >
module . exports = {
label : props . label || 'A button'
}
</ script >
< button type =" button " class =" btn " >
{{ label }}
</ button >구성 요소 사용 :
<!-- src/index.html -->
< x-button type =" submit " class =" btn-primary " label =" My button " />결과:
<!-- dist/index.html -->
< button type =" submit " class =" btn btn-primary " > My button </ button > class 및 style 속성 값을 재정의 해야하는 경우 (합병 대신) override: 속성 이름으로
<!-- src/index.html -->
< x-button type =" submit " override:class =" btn-custom " label =" My button " />결과:
<!-- dist/index.html -->
< button type =" submit " class =" btn-custom " > My button </ button > 속성을 특정 노드로 전달하려면 attributes 속성을 사용하십시오.
<!-- src/my-component.html -->
< div class =" first-node " >
< div class =" second-node " attributes >
Hello world!
</ div >
</ div >구성 요소 사용 :
<!-- src/index.html -->
< x-my-component class =" my-class " />결과:
<!-- dist/index.html -->
< div class =" first-node " >
< div class =" second-node my-class " >
Hello world!
</ div >
</ div >속성이 구문 분석되는 방식을 정의하기 위해 사용자 정의 규칙을 추가 할 수 있습니다. PosthTML-Attrs-Parser를 사용하여 처리합니다.
유효한 속성에 대한 기본 구성이 귀하에게 적합하지 않은 경우 아래 설명대로 구성 할 수 있습니다.
// index.js
const { readFileSync , writeFileSync } = require ( 'fs' )
const posthtml = require ( 'posthtml' )
const components = require ( 'posthtml-component' )
const options = {
root : './src' ,
// Add attributes to specific tag or override defaults
elementAttributes : {
DIV : ( defaultAttributes ) => {
/* Add new one */
defaultAttributes . push ( 'custom-attribute-name' ) ;
return defaultAttributes ;
} ,
DIV : ( defaultAttributes ) => {
/* Override all */
defaultAttributes = [ 'custom-attribute-name' , 'another-one' ] ;
return defaultAttributes ;
} ,
} ,
// Add attributes to all tags, use '*' as wildcard for attribute name that starts with
safelistAttributes : [
'custom-attribute-name' ,
'attribute-name-start-with-*'
] ,
// Remove attributes from all tags that support it
blocklistAttributes : [
'role'
]
}
posthtml ( components ( options ) )
. process ( readFileSync ( 'src/index.html' , 'utf8' ) )
. then ( result => writeFileSync ( 'dist/index.html' , result . html , 'utf8' ) ) <slot> 및 <fill> 로 작업하거나 구성 요소의 각 블록에 대한 구성 요소를 만들 수 있으며 두 가지를 모두 지원할 수도 있습니다.
docs-src/components/modal 내부의 예를 찾을 수 있습니다. 다음은 두 가지 접근 방식에 대한 짧은 설명입니다.
Bootstrap Modal의 구성 요소를 만들고 싶다고 가정 해 봅시다.
필요한 코드는 다음과 같습니다.
<!-- Modal HTML -->
< div class =" modal fade " id =" exampleModal " tabindex =" -1 " aria-labelledby =" exampleModalLabel " aria-hidden =" true " >
< div class =" modal-dialog " >
< div class =" modal-content " >
< div class =" modal-header " >
< h1 class =" modal-title fs-5 " id =" exampleModalLabel " > Modal title </ h1 >
< button type =" button " class =" btn-close " data-bs-dismiss =" modal " aria-label =" Close " > </ button >
</ div >
< div class =" modal-body " >
...
</ div >
< div class =" modal-footer " >
< button type =" button " class =" btn btn-secondary " data-bs-dismiss =" modal " > Close </ button >
< button type =" button " class =" btn btn-primary " > Save changes </ button >
</ div >
</ div >
</ div >
</ div >코드의 거의 3 개의 블록이 있습니다 : 헤더, 본체 및 바닥 글.
그래서 우리는 세 개의 슬롯이있는 구성 요소를 만들 수 있습니다.
<!-- Modal component -->
<div class="modal fade" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
- <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
+ <slot:header />
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
+ <slot:body />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
+ <slot:footer />
- <button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>그런 다음 다음과 같이 사용할 수 있습니다.
< x-modal
id =" exampleModal "
aria-labelledby =" exampleModalLabel "
>
< slot:header >
< h5 class =" modal-title " id =" exampleModalLabel " > My modal </ h5 >
</ slot:header >
< slot:body >
Modal body content goes here...
</ slot:body >
< slot:footer close =" false " >
< button type =" button " class =" btn btn-primary " > Confirm </ button >
</ slot:footer >
</ x-modal >또 다른 접근법은 구성 요소를 작은 구성 요소로 분할하여 속성을 각각에 전달하는 것입니다.
따라서 우리는 기본 구성 요소와 세 가지 다른 작은 구성 요소를 만듭니다.
<!-- Main modal component -->
< div class =" modal fade " tabindex =" -1 " aria-hidden =" true " >
< div class =" modal-dialog " >
< div class =" modal-content " >
< yield />
</ div >
</ div >
</ div > <!-- Header modal component -->
< div class =" modal-header " >
< yield />
</ div > <!-- Body modal component -->
< div class =" modal-body " >
< yield />
</ div > <!-- Footer modal component -->
< div class =" modal-footer " >
< yield />
</ div >그런 다음 다음과 같이 사용할 수 있습니다.
< x-modal
id =" exampleModal "
aria-labelledby =" exampleModalLabel "
>
< x-modal .header >
< h5 class =" modal-title " id =" exampleModalLabel " > My modal </ h5 >
</ x-modal .header >
< x-modal .body >
Modal body content goes here...
</ x-modal .body >
< x-modal .footer >
< button type =" button " class =" btn btn-primary " > Confirm </ button >
</ x-modal .footer >
</ x-modal >이런 식으로 말했듯이 소품을 정의하지 않고 각각의 속성을 전달할 수 있습니다.
두 가지 접근 방식을 모두 결합한 다음 슬롯이나 작은 구성 요소와 함께 사용할 수 있습니다.
<!-- Modal -->
< div
class =" modal fade "
tabindex =" -1 "
aria-hidden =" true "
aria-modal =" true "
role =" dialog "
>
< div class =" modal-dialog " >
< div class =" modal-content " >
< if condition =" $slots.header?.filled " >
< x-modal .header >
< slot:header />
</ x-modal .header >
</ if >
< if condition =" $slots.body?.filled " >
< x-modal .body >
< slot:body />
</ x-modal .body >
</ if >
< if condition =" $slots.footer?.filled " >
< x-modal .footer close =" {{ $slots.footer?.props.close }} " >
< slot:footer />
</ x-modal .footer >
</ if >
< yield />
</ div >
</ div > <!-- /.modal-dialog -->
</ div > <!-- /.modal -->이제 슬롯이나 작은 구성 요소와 함께 구성 요소를 사용할 수 있습니다.
알 수 있듯이 슬롯을 사용하여 이미 작은 구성 요소를 사용할 수 있으므로 슬롯을 통해 전달 된 모든 props 있는 $slots 슬롯을 통해 소품을 전달할 수도 있고 슬롯이 채워 졌는지 확인할 수도 있습니다.
posthtml-extend 및/또는 posthtml-modules 에서 마이그레이션하는 경우 여기에서 업데이트를 따르십시오 : Posthtml-Components/Issues/16.
PosthTML 가이드 라인 및 기여 가이드를 참조하십시오.
모든 posthtml 기고자, 특히 posthtml-extend 및 posthtml-modules 기고자 덕분에 코드의 일부로 훔친 이 플러그인에서 영감을 얻었습니다. Laravel Blade Template Engine에도 큰 감사를드립니다.