KScript 문서
KO

언어

영어에서 자동 번역되었습니다. 원문은 영어입니다.

웹 페이지

모델 폼

kscript make component은 기존 모델의 컴포넌트를 만들거나, 모델과 그 컴포넌트를 함께 만들 수 있어요:

명령어기능
kscript make component NoteCard --model Note --fields title,bodyNote를 보여 주는 컴포넌트예요.
kscript make model Note --fields "title: string, body: string" --component모델과 그 모델의 컴포넌트예요.

첫 번째 명령은 _components/note-card.kscript을 씁니다. 이 컴포넌트는 모델 이름을 딴 입력값으로 행을 받으므로, 페이지에서는 <note-card note="{$note}" />로 렌더링해요:

<import package="KScript.Web" />
<import path="../models/note.kscript" />

<type name="NoteCard" extends="Component">
  <construct>
    <field name="note" type="Note" />
  </construct>

  <fn name="render" value="```html
      &lt;section class=&quot;note-card&quot;>
        &lt;p>{$note.title}&lt;/p>
        &lt;p>{$note.body}&lt;/p>
        &lt;slot />
      &lt;/section>
      ```" />
</type>
import KScript.Web
import "../models/note.kscript"

type NoteCard extends Component {
  construct({ note: Note })

  fn render() => ```html
    <section class="note-card">
      <p>{$note.title}</p>
      <p>{$note.body}</p>
      <slot />
    </section>
    ```
}

태그의 속성이 컴포넌트의 입력값을 채우며, render()이 이를 $note로 읽어요. 계산 필드, 지역 상수, $this->method()로 호출하는 메서드도 HTML에서 쓸 수 있어요. 편집기는 태그에서 프롭을, 펜스 안에서 모델 필드를 자동 완성해요. Component에는 fn render()가 필요해요.

라우트에서 레코드를 대신 가져오려면 --inject을 추가하세요. 그러면 페이지에서 /notes/{note}에 <note-card />를 씁니다. 컴포넌트는 레코드를 받을 때 모델의 정책(policy)에 권한을 확인해요: construct({ note: Note = @inject(can: read) }). 다른 권한은 --inject update로 지정해요. @inject()로 라우트의 레코드 가져오기를 참고하세요.

모델 데이터 저장하기

컴포넌트는 KScript.Data 모델에 변경 사항을 바로 저장할 수 있어요. 쓰기를 허용할 필드와 행의 소유자를 웹 라우트에서 한 번 선언하세요. 여기서는 Profile 모델이 user_id와 bio를 가지고 있어요:

<KScript.Routes>
  <ModelUpdate name="edit_profile" model="Profile" owner="user_id" fields="bio" />
</KScript.Routes>
import KScript.Http

Routes {
  ModelUpdate(name: edit_profile, model: Profile, owner: user_id, fields: [bio])
}

그다음 편집기를 생성하세요:

명령어기능
kscript make component ProfileEditor --model-update edit_profile바이오를 저장하는 폼이에요.

소유한 행을 <profile-editor profile="{$profile}" />로 전달하세요. 보호된 GET 컨트롤러가 로그인한 사용자의 행을 불러와 페이지에 넘기면, 페이지는 <profile-editor profile="{$data.profile}" />를 렌더링해요. 인증 샘플에 이 프로필 편집기와 마이그레이션이 포함되어 있어요. 자체 대화형 상태를 가진 컴포넌트라면 kscript make component OrderDetails --live부터 시작하세요.

생성된 폼은 저장 버튼을 클릭하면 저장돼요. 입력 중에는 저장 전까지 데이터베이스가 바뀌지 않아요. 라이브 블록 안에서는 저장 시 모델이 제자리에서 갱신되고 메시지로 확인돼요. 라이브 블록 밖의 폼은 평소처럼 POST 후 리디렉션되므로, 자바스크립트를 끈 상태에서도 동작해요.

입력이 멈추면 저장하도록 --autosave을 추가하거나, autosave="750ms"로 지연 시간을 지정하세요(기본은 500ms). 저장 버튼은 여전히 대기 중인 수정 사항을 바로 보내요. 런타임은 수정된 필드만 보내고, 각 저장이 끝날 때까지 기다리며, 검증에 실패하면 임시 입력값을 유지해요.

저장 시 검사하는 방식

KScript가 POST 핸들러를 작성하고 CSRF 토큰을 포함해요. 모든 저장은 세션과 토큰을 확인하고, 행의 user_id가 로그인한 사용자의 id와 일치하는지 확인하며, 필드를 모델과 바인딩의 필드 목록에 맞춰 검증해요. 행의 키가 계정 id일 때는 owner: id를 사용하고, 자체 권한이 필요하면 라우트 미들웨어에 ModelUpdate를 추가하세요. 행을 읽을 때도 소유권을 확인하세요. 직접 만든 SQLite 파일은 공개 사이트 밖에 두거나, 이름이 _로 시작하는 폴더에 두세요.