Yusuf
Yusuf

Reputation: 53

Avoiding excessive if/else statements in Templates

When there is membership system we just show something only for users.. For example, register and log in button is for non-members or users that haven't logged in yet. Sametime, log out button is just for users that already logged in.

I use a mvc system that I created before. What type of methods or classes do you create to escape the use of if/else statements ?

Upvotes: 0

Views: 57

Answers (2)

edi9999
edi9999

Reputation: 20564

If you're using too many if/else statements, you're probably not using template inheritance.

Basically you have a master template:

master.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
   @section('main')
   @endsection()
</body>
</html>

The other templates inherit this template

user.html:

@extends('master')
@section('main')
<button>Connect</button>
@endsection

visitor.html

@extends('master')
@section('main')
<button>Subscribe</button>
@endsection

Most of the templating systems offer a kind of template inheritance, like the Twig templating language.

This advice is also applicable in other parts of your code, eg if you're using too many if else or switch case, you could probably create Classes that inherit your current class.

The syntax used for the code samples is inspired by Laravel's Blade templating language

Upvotes: 1

Snehal S
Snehal S

Reputation: 875

You can maintain a session and check it every time, even after reloading page.

i.e after login or registration create an array and store t in a session and then check whether that session is empty or not. If that session is not empty that means user is logged in and clear that session after user clicks on logout button.

With this logic you can handle all your operations.

Upvotes: 0

Related Questions