mojolicious referencing a stash variable not always defined

我只是一个虾纸丫 提交于 2019-12-10 02:36:58

问题


I am still learning mojolicious and MVC frameworks in general so this just might be a problem where I am thinking about this wrong so if I am please suggest a better way to do the following.

I have a route /route/:param where param is sometimes defined and sometimes not. I am trying to use "param" in the template for that route but I get an error saying "param" requires explicit package name. I know this is due to :param not matching in the route because when I do call /route/value everything works fine.

Is there a way to be able to use the same template for both when "param" is defined and not defined? I am just trying to pre-populate a form off of what is defined in "param" but not making it required to.

In the template I have

<% if(defined($param)){ %><%= $param %><% } %>

Thanks.


回答1:


It is always safe to refer to stash("param"), where stash is a helper function defined in Mojolicious::Plugin::DefaultHelpers:

<%= stash "param" %>
<%= defined(stash("param")) && stash("param") %>
etc.



回答2:


It seems like in this situation using an optional placeholder in the route might be the best option. If the placeholder is defined in the route itself that definition will be used if the placeholder is not given in the url (else the value specified in the URL is used).

For example:

$r->any('/page/:paramVar')->to('page#doTheThing', paramVar => 'cake');

If the the address "/page" is loaded then $self->param('paramVar') == 'cake' else if "/page/tree" is loaded then $self->param('paramVar') == 'tree'.

Note: As with other placeholder values an optional placeholder, such as paramVar used in the above example, can be accessed via the stash function as well as the param function: $self->stash('paramVar').




回答3:


It is possible to define a stash (or a flash) variable as a Perl variable within the epl space/template so that it can be reused, if required. e.g.,

% if (my $param = stash 'param') {                                  
    $param
% }

In this case the if condition block will be rendered only when the param is defined in the stash, otherwise, it'll be skipped.



来源:https://stackoverflow.com/questions/16943439/mojolicious-referencing-a-stash-variable-not-always-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!