3

I have 2 tables : business and article.

And I have 3 controllers : Home, Articles, Businesses.

In Home page controller the following code returns a list of Businesses and Articles:

     def index(): 
       lists= db().select(db.article.ALL,limitby=(0, 5),orderby=~db.article.id)
       listings=db().select(db.business.ALL)
       return dict(lists=lists,listings=listings)

with a loop in the home view file.

So I want to link articles to the Articles controller and Businesses to the Business controller from the home page...I have used the following code:

    def show(): 
      myid == request.vars.id
      redirect(URL(c='businesses',f='show?id=%s'% myid))

So even articles list will link to Business controller now using the function show in Business controller, but I want use if and elif according to the respective listing.

David Nehme
  • 21,379
  • 8
  • 78
  • 117
praveen
  • 41
  • 3

1 Answers1

5

Instead of a redirect, why not just link directly to the show() function in each controller, and set up the URLs as follows:

{{for article in lists:}}
<a href="{{=URL('article', 'show', args=article.id)}}">{{=article.title}}</a>
{{pass}}

and similarly for the business links.

In article.py:

def show():
    article = db(db.article.id == request.args(0)).select().first()
    return dict(article=article)

Another option is using just a single show() function in your main controller to handle both articles and businesses. In that case, links would look like this:

Article: URL('home', 'show', args=['article', article.id])

Business: URL('home', 'show', args=['business', business.id])

and in home.py:

def show():
    item = db(db[request.args(0)].id == request.args(1)).select().first()
    return dict(item=item)

The show.html view could then include logic to display an article and a business differently (depending on the value of request.args(0)), or the show() function could explicitly set alternative article.html and business.html views as follows:

    response.view = 'home/%s.html' % request.args(0)

Side Note: The URLs will look nicer if you make the record id an arg instead of a var (i.e., /show/1 instead of /show?id=1). Also, if you do need to specify vars in the URL() function, do not explicitly append them to the function name as a query string (i.e., don't do URL(..., f='show?id=%s' % myid)) -- instead, use the vars argument (i.e., URL(..., f='show', vars=dict(id=myid))).

Anthony
  • 25,466
  • 3
  • 28
  • 57