erlangnitrogen

How to call an erlang function in nitrogen?


-module (blah).
-compile(export_all).
-include_lib("nitrogen_core/include/wf.hrl").

main() -> #template { file="./site/templates/bare.html" }.

title() -> "Welcome to Nitrogen".

body() ->
#button { id=calcButton, text="Click"}.

imafunction(Param1, Param2) -> %something here%.

How do you call the imafunction(Param1, Param2) function with its parameters by clicking the button?


Solution

  • You're going to want to do this with a postback.

    The simplest way is to change your button to include a postback attribute:

    #button { id=calcButton, text="Click", postback=do_click}.
    

    Then you have to handle the postback with an event/1 function:

    event(do_click) -> 
        imafunction("first val","second val").
    

    But if you wanted to pass the values along with some kind of dynamic data, you can do this one of two ways.

    1) You can pass it as part of the postback, and pattern match on the postback value.

    #button { id=calcButton, text="Click", postback={do_something,1,2} }
    

    And then pattern match on the postback

    %% Notice how this is matching the tuple in the postback
    event({do_something,Param1,Param2}) ->
        imafunction(Param1,Param2).
    

    or, 2) You can pass the values as input (say a textbox or dropdown box)

    First, add your param fields to send, and make sure your button does a postback

    body() ->
        [
            #label{text="Param 1"},
            #textbox{id=param1},
            #br{},
            #label{text="Param 2"},
            #textbox{id=param2},
            #br{},
            #button{ id=calcButton, text="Click", postback=do_other_thing}
       ].
    

    Then in your event/1 function, we'll retrieve the values and call your function.

    event(do_other_thing) ->
        Param1 = wf:q(param1),
        Param2 = wf:q(param2),
        imafunction(Param1,Param2).
    

    You can read more about Nitrogen Postbacks and Submitting data at