Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: a simple web front end

by haukex (Bishop)
on Oct 28, 2020 at 21:07 UTC ( #11123278=note: print w/replies, xml ) Need Help??


in reply to a simple web front end

So i fill textarea, press submit and... i get raw json response in my browser. Question is: How do i separate "api" from "frontend" and made them pass data between each other in order to - have nice form

Note you can seprate your API from the frontend purely on the Perl level. Mojolicious includes content negotiation, as I show in the following example (run it e.g. via morbo script.pl). Note how POST and GET just work, including http://127.0.0.1:3000/myform?foo=helloworld&format=json and http://127.0.0.1:3000/myform.txt?foo=blahblah.

#!/usr/bin/env perl use Mojolicious::Lite -signatures; any '/' => sub ($c) { $c->redirect_to('/myform.html') }; sub my_api_do_thing ($arg) { # could/should be in a module! return $arg =~ s/[aeiou]//gr; } any '/myform' => sub ($c) { if ( defined $c->param('foo') ) { # if the form was submitted $c->stash( returnval => my_api_do_thing( $c->param('foo') ) ); } $c->respond_to( json => { json => { retval => $c->stash('returnval') } }, txt => { text => $c->stash('returnval') }, html => { template => 'myform' }, ); }; app->start; __DATA__ @@ myform.html.ep % layout 'main', title => 'Hello, World!'; <div> % if ( stash 'returnval' ) { <div> Return value: <%= stash 'returnval' %> </div> % } %= form_for myform => ( method=>'post' ) => begin <div> %= label_for foo => 'Foo' %= text_field foo=>'Foobar?' </div> <div> %= radio_button format => 'html', id=>'format_html', checked => un +def %= label_for format_html => 'HTML' %= radio_button format => 'json', id=>'format_json' %= label_for format_json => 'JSON' </div> <div> %= submit_button </div> %= end </div> @@ layouts/main.html.ep <!DOCTYPE html> <html> <head><title><%= title %></title></head> <body> %= content </body> </html>

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11123278]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2021-07-26 17:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?