你可以将 Tiptap 与 Laravel、Livewire、Inertia.js、Alpine.js、Tailwind CSS,甚至—是的,你没看错—在 PHP 中一起使用。

我们提供了 官方 PHP 包来处理 Tiptap 内容,你可以将 Tiptap 兼容的 JSON 转换为 HTML,反之亦然,清理内容,或者修改它。

Laravel Livewire

my-livewire-component.blade.php

  1. <!--
  2. 在你的 Livewire 组件中,你可以添加一个
  3. 自动保存方法,用来每 10 秒保存一次编辑器的内容
  4. -->
  5. <x-editor wire:model="foo" wire:poll.10000ms="autosave"></x-editor>

提示

在 Livewire v3 中,.defer 修饰符不再可用,因为默认情况下,状态更新会被延迟。如果你需要在服务器端更新状态,可以使用 .live 修饰符,因为它会有所变化。

editor.blade.php

  1. <div
  2. x-data="setupEditor(
  3. $wire.entangle('{{ $attributes->wire('model')->value() }}').defer
  4. )"
  5. x-init="() => init($refs.editor)"
  6. wire:ignore
  7. {{ $attributes->whereDoesntStartWith('wire:model') }}
  8. >
  9. <div x-ref="editor"></div>
  10. </div>

index.js

  1. import { Editor } from '@tiptap/core'
  2. import StarterKit from '@tiptap/starter-kit'
  3. window.setupEditor = function (content) {
  4. let editor
  5. return {
  6. content: content,
  7. init(element) {
  8. editor = new Editor({
  9. element: element,
  10. extensions: [StarterKit],
  11. content: this.content,
  12. onUpdate: ({ editor }) => {
  13. this.content = editor.getHTML()
  14. },
  15. })
  16. this.$watch('content', (content) => {
  17. // 如果新内容与 Tiptap 的内容相同,我们就跳过。
  18. if (content === editor.getHTML()) return
  19. /*
  20. 否则,意味着外部源(如 Livewire 本身)
  21. 正在修改此 Alpine 组件中的数据。
  22. 在这种情况下,我们只需要更新 Tiptap 的内容,完成即可。
  23. 更多关于 `setContent()` 方法的信息,参见:
  24. https://www.tiptap.dev/api/commands/set-content
  25. */
  26. editor.commands.setContent(content, false)
  27. })
  28. },
  29. }
  30. }