To create a dynamic, efficient, and maintainable layout that adapts to both Left-to-Right (LTR) and Right-to-Left (RTL) languages without duplicating your HTML structure or relying heavily on Blade conditionals and separate stylesheets, you can leverage the dir attribute in HTML and CSS's :dir pseudo-class. This approach ensures that your layout direction changes seamlessly based on the selected language.
Here's a step-by-step guide to achieving this:
-
Set the dir Attribute Dynamically:
Instead of using Blade conditionals to load different HTML structures or stylesheets, set the dir attribute directly on the <html> tag based on the current locale. This attribute informs the browser of the text direction, allowing CSS to adjust accordingly.
-
Use CSS to Handle Direction-Specific Styles:
Utilize CSS to adjust styles based on the dir attribute. This eliminates the need for separate CSS files for RTL and LTR, reducing duplication and maintenance overhead.
-
Single HTML Structure:
Maintain a single HTML structure that adapts to both directions. This ensures consistency and reduces the complexity of your codebase.
-
Leverage Bootstrap's RTL Support:
Bootstrap offers RTL support which can be conditionally loaded based on the dir attribute. This ensures that your components adjust their direction automatically.
Below is the refactored version of your provided Blade template implementing the above approach:
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}" dir="{{ app()->getLocale() == 'ar' ? 'rtl' : 'ltr' }}">
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ __('sas_radius_pro_dashboard') }}</title>
<!-- Stylesheets -->
<link rel="stylesheet" href="css/style.css" />
<!-- Bootstrap -->
@if (app()->getLocale() == 'ar')
<!-- Bootstrap RTL -->
<link rel="stylesheet" href="css/bootstrap-rtl.css" />
@else
<!-- Bootstrap LTR -->
<link rel="stylesheet" href="css/bootstrap.css" />
@endif
<!-- Font Awesome -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<!-- DataTables -->
<link
rel="stylesheet"
href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css"
/>
</head>
<body>
<div class="overflow_sidebar"></div>
<div class="sidebar">
@include('include.sidebar')
</div>
<div class="content_page">
<!-- Include Header -->
@include('include.header')
<!-- Main Content -->
<div class="main_content_tables">
<div class="conetnt_table">
<div class="path">
<span>{{ __('home') }}</span> /
<span>{{ __('groups') }}</span>
</div>
<div class="head_table">
<div class="info">
<p class="text_details">
<i class="fa-solid fa-people-group"></i>
{{ __('Group List | Found :count Entries', ['count' => count($allData)]) }}
</p>
</div>
<div class="input_search">
<input type="text" placeholder="{{ __('search_placeholder') }}" />
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="w-6 h-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"
></path>
</svg>
</div>
<div class="utils">
<div class="actions_box">
<button class="btn_actions">
<i class="fa-solid fa-wrench"></i>
{{ __('operations') }}
</button>
<div class="box box_utils">
<a href="{{ route('addmgrp') }}" class="item">
<i class="fa-solid fa-plus"></i>
<span>{{ __('add') }}</span>
</a>
<a id='aview' href="{{ route('prfgrp') }}" class="item">
<i class="fa-solid fa-eye"></i>
<span>{{ __('view') }}</span>
</a>
<a href="{{ route('addgrop') }}" class="item">
<i class="fa-solid fa-envelope"></i>
<span>{{ __('send_message') }}</span>
</a>
<div class="item btn_open_model" data-model="1">
<i class="fa-solid fa-right-left"></i>
<span>{{ __('move_clients') }}</span>
</div>
<div class="item">
<i class="fa-solid fa-users-slash"></i>
<span>{{ __('delete_clients') }}</span>
</div>
<div class="item">
<i class="fa-solid fa-trash"></i>
<button id="deletebtn">
<span>{{ __('delete') }}</span>
</button>
</div>
</div>
</div>
<div class="reload">
<button class="btn_utils">
<i class="fa-solid fa-repeat"></i>
</button>
</div>
<div class="filter">
<button class="btn_utils">
<i class="fa-solid fa-filter"></i>
</button>
</div>
</div>
</div>
<div class="container_table">
<table id="table" class="display" style="width: 100%">
<thead>
<tr>
<th>
<input type="checkbox" id="selectAll" />
</th>
<th>{{ __('name') }}</th>
<th>{{ __('clients') }}</th>
<th>{{ __('notes') }}</th>
<th>{{ __('creation_date') }}</th>
</tr>
</thead>
<tbody>
@if($allData)
@foreach($allData as $data)
<tr>
<td>
<input type="checkbox" />
</td>
<td>
<a href="profile-group.html">{{ $data->name }}</a>
</td>
<td>{{ __('all_clients') }}</td>
<td>{{ $data->comment }}</td>
<td>{{ $data->created_at->format('Y-m-d H:i:s') }}</td>
</tr>
@endforeach
@endif
<!-- Add the rest of your table rows here -->
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Start Modal Add Group -->
<div class="overflow"></div>
<div class="model_poup" data-model="1">
<div class="content">
<div class="head">
<h5 class="title_model">{{ __('groups') }}</h5>
<div class="close_model">
<i class="fa-solid fa-xmark"></i>
</div>
</div>
<form action="">
<div class="input_item">
<label for="">{{ __('select_group') }}</label>
<select name="" id="">
<option value=""></option>
<option value="">{{ __('all_clients') }}</option>
</select>
</div>
<button class="btn_submit">{{ __('confirm') }}</button>
</form>
</div>
</div>
<!-- End Modal Add Group -->
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/model.js"></script>
<script src="js/tableUtils.js"></script>
<script src="js/boxs-header.js"></script>
<script src="js/sidebar.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const selectedPhones = new Set();
const checkboxes = document.querySelectorAll('tbody input[type="checkbox"]');
const deleteBtn = document.getElementById('deletebtn');
const selectAllCheckbox = document.getElementById('selectAll');
// Handle Select All
selectAllCheckbox.addEventListener('change', function () {
const isChecked = this.checked;
checkboxes.forEach(checkbox => {
checkbox.checked = isChecked;
const phone = checkbox.closest('tr').querySelector('td:nth-child(2)').textContent.trim();
if (isChecked) {
selectedPhones.add(phone);
const row = checkbox.closest('tr');
const data = {
name: row.cells[1].textContent.trim(),
customertype: row.cells[2].textContent.trim(),
created_at: row.cells[4].textContent.trim()
};
fetch('api/data/profile-client-groups', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify(data)
});
console.log('Added:', phone, data);
} else {
selectedPhones.delete(phone);
console.log('Removed:', phone);
}
});
});
// Handle Individual Checkbox Change
checkboxes.forEach((checkbox) => {
checkbox.addEventListener('change', function () {
const row = this.closest('tr');
const phone = row.querySelector('td:nth-child(2)').textContent.trim();
if (this.checked) {
selectedPhones.add(phone);
const data = {
name: row.cells[1].textContent.trim(),
customertype: row.cells[2].textContent.trim(),
created_at: row.cells[4].textContent.trim()
};
fetch('api/data/profile-client-groups', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify(data)
});
console.log('Added:', phone, data);
} else {
selectedPhones.delete(phone);
console.log('Removed:', phone);
}
});
});
// Handle Delete Button Click
deleteBtn.addEventListener('click', function () {
if (selectedPhones.size > 0) {
deleteSelectedRows();
}
});
// Delete Selected Rows Function
function deleteSelectedRows() {
console.log('Phones to delete:', Array.from(selectedPhones));
fetch('/delete-rows-groups', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify({ phones: Array.from(selectedPhones) })
})
.then(response => response.json())
.then(data => {
if (data.success) {
selectedPhones.forEach(phone => {
const rows = document.querySelectorAll('tbody tr');
rows.forEach(row => {
if (row.querySelector('td:nth-child(2)').textContent.trim() === phone) {
row.remove();
}
});
});
selectedPhones.clear();
alert('{{ __("selected_rows_deleted_successfully") }}');
} else {
alert('{{ __("error_deleting_rows") }} ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('{{ __("an_error_occurred_while_deleting_rows") }}');
});
}
// Function to Send Profile Data
function sendreqprofile() {
fetch('/handleprofilegroupdata', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify({ /* populate with necessary pdata */ })
})
.then(response => response.json())
.then(data => {
console.log('{{ __("profile_data_sent_successfully") }}', data);
})
.catch(error => {
console.error('{{ __("error_sending_profile_data") }}', error);
});
}
// Handle View Button Click
const viewIdBtn = document.getElementById('aview');
if (viewIdBtn) {
viewIdBtn.addEventListener('click', function (e) {
e.preventDefault();
console.log('Button clicked!');
sendreqprofile();
});
} else {
console.error('{{ __("button_aview_not_found") }}');
}
// Initialize DataTables
$("#table").DataTable({
pagingType: "full_numbers",
scrollX: true,
});
});
</script>
</body>
</html>
Key Improvements and Explanations:
-
Direction Handling with dir Attribute:
<html lang="{{ app()->getLocale() }}" dir="{{ app()->getLocale() == 'ar' ? 'rtl' : 'ltr' }}">
- The
dir attribute is set based on the current locale. If the locale is Arabic ('ar'), it sets the direction to RTL; otherwise, it defaults to LTR.
- This approach removes the need for separate HTML blocks for different languages, streamlining your template.
-
Single HTML Structure:
- Both Arabic and English versions now share the same HTML structure. The direction changes dynamically based on the
dir attribute, ensuring consistency and reducing duplication.
-
Conditional Loading of Bootstrap CSS:
@if (app()->getLocale() == 'ar')
<!-- Bootstrap RTL -->
<link rel="stylesheet" href="css/bootstrap-rtl.css" />
@else
<!-- Bootstrap LTR -->
<link rel="stylesheet" href="css/bootstrap.css" />
@endif
- Only the necessary Bootstrap CSS (RTL or LTR) is loaded based on the language. This ensures that Bootstrap components render correctly in both directions without overwhelming the browser with unnecessary styles.
-
Optimized JavaScript:
- Combined Event Listeners: The JavaScript now initializes all event listeners within the
DOMContentLoaded event to ensure the DOM is fully loaded before scripts run.
- Removed Redundant Code: By having a single HTML structure, there's no need to duplicate JavaScript for different language versions.
- Enhanced Accessibility: The
deleteSelectedRows and sendreqprofile functions are encapsulated and handle both directions seamlessly.
-
CSS Adjustments Based on Direction:
-
Improved Accessibility and Semantics:
Additional Recommendations:
By implementing the above approach, you create a more maintainable, efficient, and scalable application that dynamically adapts to different languages and their respective text directions without unnecessary duplication or complexity.