Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add multi-format doc #33

Merged
merged 2 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ Topics
turbo_frame.md
turbo_stream.md
real-time-updates.md
multi-format.md
redirect.md
test.md
61 changes: 61 additions & 0 deletions docs/source/multi-format.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Multi-format Response

In Ruby on Rails, `respond_to` is a method that allows you to define how your controller should respond to different types of requests.

```ruby
class PostsController < ApplicationController
def create
@post = Post.new(post_params)

respond_to do |format|
if @post.save
format.turbo_stream { render turbo_stream: turbo_stream.append(@post) }
format.json { render json: @post, status: :created }
format.html { redirect_to @post, notice: 'Post was successfully created.' }
else
format.turbo_stream { render turbo_stream: turbo_stream.replace('new_post', partial: 'posts/form', locals: { post: @post }) }
format.json { render json: @post.errors, status: :unprocessable_entity }
format.html { render :new }
end
end
end
end
```

In the above code, developer can return different response format based on request `Accept` header.

We can do similar approach with `turbo_helper`

```python
from turbo_helper import (
ResponseFormat,
response_format,
)

class TaskCreateView(LoginRequiredMixin, CreateView):
def form_valid(self, form):
response = super().form_valid(form)
request = self.request
messages.success(request, "Created successfully")

with response_format(request) as resp_format:
if resp_format == ResponseFormat.TurboStream:
return TurboStreamResponse(
render_to_string(
"demo_tasks/partial/task_create_success.turbo_stream.html",
context={
"form": TaskForm(),
},
request=self.request,
),
)
else:
return response
```

Notes:

1. If the client `Accept` turbo stream, we return turbo stream response.
2. If not, we return normal HTML response as fallback solution.
3. This is useful when we want to migrate our Django app from normal web page to turbo stream gradually.
4. If you are using Python 3.10+, you can use `match` statement instead of `if` statement.