What should not be inside an MVC view?
From the limited amount of people that I've talked to regarding MVC web frameworks, I've heard people say that, forgettin开发者_StackOverflow社区g about forms, a view file should ideally contain HTML markup, string manipulation and a few for each
loops. I've also been told that if
statements in views should be avoided if at all possible. Is this generally agreed?
EDIT: The situation that has inspired this question is writing a navigation, I'm finding myself writing:
if secondary_navigation_item has children
...
I'm thinking, ideally, does this qualify as logic (that should not be here)?
Generally speaking, the View should not contain any server-side business logic. But it can still contain logic that directly pertains to rendering the view.
An example would be a view containing some sort of variant record, whose display depends on the setting of a particular field. For example, a record that displays different information depending on a sex field being set to male or female. Which, of course, would require an if
statement.
To say that your views should not contain any conditional logic is just silly. How else would you generate UI elements like "new message" icons or flash messages—use a different view template for every possible interface state? It's like saying that your controller should not contain any variable assignments because data manipulation belongs in the model.
It's perfectly alright to have logic in your view as long as it's view-related logic. You shouldn't get caught up in absolutes or pedantic interpretations of the model-view-controller definitions. As long as you understand and apply the underlying concepts of MVC, you're on the right track.
Every rule has an exception, and there are cases where you would do string manipulating in a controller or even implement application flow in the view. Sometimes you just have to evaluate it on a case-by-case basis and apply a little common sense.
A view should basically contain:
- HTML Markup
- Javascript
- CSS
- Minimum of server-side code you may need to put into view
So, a View should typically contain the layout elements. The main processing logic should go in Controller.
More Info:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
精彩评论