DEV Community

Seijiro Ozawa
Seijiro Ozawa

Posted on

2

django-react-templatetagsでdjangotemplateからreact コンポーネントを描画する

はじめに

この記事は django advent calendar 12日目の記事です。

今回は django-teact-templatetagsを紹介させていただきたいと思います。

https://github.com/Frojd/django-react-templatetags

特徴

  • サーバーサイドから django template をレスポンスを行う
  • pythonのモデルを componentsに渡す データに変換可能なMixin
  • SSR をサポート(未検証)

機能としてはたったこれだけですが、SPAでないアプリケーションにreactを導入したい場合やSSRしたい場合には重宝すると思いました。

使い方

基本的にREADMEの通りにすればOK
https://github.com/Frojd/django-react-templatetags/blob/develop/README.md

  • installed_app に追加
INSTALLED_APPS = (
    # ...
    'django_react_templatetags',
)

  • context_processor に追加
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            'templates...',
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'debug': True,
            'context_processors': [
                ...
                'django_react_templatetags.context_processors.react_context_processor',
            ],
        },
    },
]

  • django templateに load react と {% react_render component="Component" props=my_data %} を追加
 {% load react %}

<body>
<p>...something</p>
{% react_render component="Component" props=my_data %}
{% react_print %}
</body>
  • modelからreact-componentに変換

READMEを参考に RepresentationMixin を実装するだけです。
https://github.com/Frojd/django-react-templatetags#working-with-models

使ってみた困った所

フロントエンドを今どきの作りにした場合は webpackやgulp からコンパイルされ、minifyされてjavascriptを読み込むと思います。

その際にはjsのトップレベルがローカルクロージャとなる場合が多く サーバに描画されたhtmlからreact-componentがスコープの対象外になりました。

最終的には(極力避けたかったのですが)ビルドされるjavascript内でブラウザのwindow変数に トップレベルの ReactComponentを代入するようにしました。

// こんなかんじのコードをrootに置く
const RootComponent = require("./Root")

window.RootComponent= RootComponent

まとめ

ライブラリそのものは薄く設計を工夫すれば捨てるのが容易で pythonのモデルからjavascriptへのデータ受け渡しまでサポートしてもらえるので個人的には結構アリな選択肢かと思いました。

特に従来のWebAppに部分的にReactを導入したい場合などは適していると思います。

また、今回は試していませんがSSRしたい場合も選択肢に入って良いと思います。

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay