I am creating a Twitter Tweet Analysis web page. I want to localize the page based on the user selection. On the header I am providing a nav bar : Country which lists different locales. Based on the country selected by the user, the entire webpage should get translated.
Here is my HTML header:
<header>
<div class="navbar navbar-default navbar-fixed-top">
<div class="navbar-header">
<a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="navbar-brand" href="#">Twitter Analysis</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav ">
<li class="dropdown">
Country
<ul class="dropdown-menu">
<li>United States</li>
<li>China</li>
</ul>
</li>
</ul>
</div>
</div>
</header>
Any idea how I should implement this? Please advice. Thanks
You can use i18n-2 module for this.
First, you need to install i18n-2 using npm
$ npm install --save i18n-2
After that, add these config line into your app.js file. Remember to add it after you have loaded the cookieParser.
var cookieParser = require('cookie-parser');
app.use(cookieParser('your secret here')); // put the config after this line
i18n.expressBind(app, {
// setup some locales - other locales default to vi silently
locales: ['vi', 'en'],
// set the default locale
defaultLocale: 'vi',
// set the cookie name
cookieName: 'locale'
});
// set up the middleware
app.use(function(req, res, next) {
req.i18n.setLocaleFromQuery();
req.i18n.setLocaleFromCookie();
next();
});
The i18n object will now reside within the request object of each request. The above config also allows the locale to be set from query string or from cookie. For example, the mysite.com/?lang=en will automatically set the locale to en. To use the i18n object, simply use the __ function
function handlerFunc1(req, res){
res.render('index', { title: req.i18n.__("hello") });
}
Or if you want to use it in your view, simply use __ again
<h1>
<%= __("hello") %>
</h1>
i18n-2 will then look up the key hello in the locale files (by default located in locales/en.js and locales/vi.js). If the keys or the files is not exist yet, it will then create those files and keys automatically for you so you don’t have to worry about the errors. You can then open those files and edit the values already there or add your new one. The file syntax is just normal JSON syntax.
Note: you cannot use // for comments.
{
"hello": "Hello",
"title": "title",
}
To change the language, you can set it directly using setLocale(locale) function. Beside that, you can set the cookie locale value for the browser to remember the current language for the next access.
function handlerFunc(req, res){
// you can set it directly like this
req.i18n.setLocale('vi');
// or set it via the cookie
res.cookie('locale', 'vi');
req.i18n.setLocaleFromCookie();
// redirect back
res.redirect('back');
};
Source - link
Related
After intergrating Bootstrap 4 to my ASP MVC Core web project and changing some HTML code to a Cookie Policy window. I noticed the accept button no longer functions. The button is there and you can click on it but it dosen't respond.
Besides changing some of the HTML for the cosmetic appearance the only other change made was the removal of a div tag which defined a container class for the text content. The JQuery code listed remains unchanged.
The function is called by a tag located in the _Layout.cshtml file within the Visual Studio project. It was functioning before the change were made to the code.
Any positive insight would be helpful. Especially if there is something that I have missed or have out of alignment.
using Microsoft.AspNetCore.Http.Features
#{
var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
var showBanner = !consentFeature?.CanTrack ?? false;
var cookieString = consentFeature?.CreateConsentCookie();
}
#if (showBanner)
{
<nav id="cookieConsent" class="navbar navbar-light fixed-bottom float-sm-left"
style="background-color:transparent" role="alert">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#cookieConsent .navbar-collapse">
<span class="sr-only">Toggle cookie consent banner</span>
<span class="navbar-toggler-icon"></span>
</button>
<span class="navbar-brand"><span class="text-info" aria-hidden="false"></span></span>
<div class="collapse navbar-collapse" style="background-color:rgba(49, 67, 179, 0.80); color:lightgoldenrodyellow">
<div class="container-fluid">
<h4><strong>COOKIE AND PRIVACY POLICY </strong></h4>
<p class="navbar-text" style="color:yellow">
This web site uses cookies and other technologgy for features and functions to
be viewed and operate normaly. You can acknowledge the site uses these features
by clicking the "Accept" button to the right of this message window. To view the
sites "Cookie and Privacy" policy page, click on the "Cookie and Privacy
Information" button.
</p>
<p class="navbar-text" style="color:whitesmoke">
NOTE: Clicking on the "Accpt" button only acknowledges you have read this
this message and is not a condition for access to this site.
</p>
</div>
<div class="nav-container float-right">
<a asp-controller="Home" asp-action="Privacy" class="btn btn-info navbar-btn">Cookie and Privacy Information</a>
<button type="button" class="btn btn-light navbar-btn" data-cookie-string="#cookieString">Accept</button>
</div>
</div>
</nav>
<script>
(function () {
document.querySelector("#cookieConsent button[data-cookie-string]").addEventListener("click", function (el) {
document.cookie = el.target.dataset.cookieString;
document.querySelector("#cookieConsent").classList.add("hidden");
}, false);
})();
</script>
}
It seems that adding hidden class is failed . If you want to hide the cookieConsent nav after clicking accept button , you could try the following two approaches :
add some css for the class "hidden" in the path wwwroot/css/site.css , the JQuery code listed remains unchanged.
.hidden {
display: none;
}
change the JQuery like below :
document.querySelector("#cookieConsent").setAttribute("hidden","true");
I'm working with Bootsrtap 4 and I'm trying to add the class active to my nav-item elements whenever their nav-link href attribute is the same as the current url.
On the html side, I uesd a basic url generator as shown below:
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{{ url('/brands') }}" role="button">Brands</a>
</li>
<!-- ... -->
</ul>
And then I used a jQuery method to compare them with the current url:
$('.navbar-nav .nav-item .nav-link').each( () => {
// If the current path and the link url are the same...
if ($(this).attr('href').indexOf(location.pathname) !== 1) {
// ...then add the class 'active' to 'nav-item', its parent
$(this).parent().addClass('active')
}
})
However, I noticed that $(this).attr('href') was undefined, probably because it's a generated url, and therefore nav-item doesn't get the active class.
EDIT: as an example, for now it's a very basic url, without parameter, which looks like this:
http://domain.example/brands
Does anyone know how to solve this problem? Thanks in advance.
I'd recommend you to go another way. Instead of "activating" the link with jQuery, you could easily do it server-side with Laravel:
<ul class="navbar-nav">
<li class="nav-item">
<a class="{{ Request::is('brands*') ? 'nav-link active' : 'nav-link' }}"
href="{{ url('/brands') }}"
role="button">Brands</a>
</li>
<!-- ... -->
</ul>
Explanation:
Laravel uses the template-engine twig for rendering the HTML server-side. Instead of manipulation the DOM client-side, you can easily add an conditional to check for the current request parameters. Laravel gives you nativeliy the possibility to check the request path even with a wildcard.
Your problem is most likely caused by the difference between using () => {} or function () {}
When you use the arrow syntax the prop this is unbound. Meaning that also $(this) will return an empty jQuery object instead of returning the anchor. Any follow up jQuery chaining will return something empty/undefined.
So, changing .each( () => { to .each(function() { will at least fix your undefined problem.
Information about the arrow syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Okay this is what i do generally do in all my laravel projects when it comes to make sidebar or any link "active" on click :-
<li class="nav-item {{ in_array(Route::currentRouteName(),[
'admin.dashboard',
'admin.updates',
])? 'active show' : ''}}">
<i class="typcn typcn-clipboard"></i>Dashboard
<nav class="nav-sub">
Home
</nav>
</li>
Now notice this {{ BladeHelper::sideBar_link_isActive('admin.dashboard') }}
I created dynamic helper function to get the current url and return "active" class
Path : app\Helpers\BladePageHelper
<?php
namespace App\Helpers;
use Route;
class BladePageHelper
{
public static function sideBar_link_isActive($selectedLink){
$currentRouteName = Route::currentRouteName();
if($selectedLink === $currentRouteName){
return 'active';
}else{
return '';
}
}
}
I'm using route name here like
Route::("/","MyController#mymethod")->name("myname")
You can do this with url too.
I hope this helps.
Happy Coding
I am trying to render an image on my React Web App, but the image is broken. However, when I do a console.log of the file's path, I see the following which seems to be correct.
We are using url-loader and file-loader with webpack, and am importing the file path directly in the import statements as required. I have tried adding required ('imageFilePath.png'), but that did not work either.
Currently, the image is placed directly in the src folder along with App.js.
Here is my App.js:
import React, { Component } from 'react'
import './App.css'
import {Tweet} from 'react-twitter-widgets';
import logoFinal from './logoFinal.png';
class App extends Component {
render () {
const { error, isLoaded} = this.state;
if (error){
return <div> Error: {error.message}</div>
} else if (!isLoaded){
return <div>Loading...</div>
} else{
return (
<div className="container">
<nav className="navbar navbar-expand-lg navbar-light fixed-top">
<div className="container">
<a className="navbar-brand pull-left" href="/home">
<div>
<img src={require('./logoFinal.png')} width='100' margintop='-7' /></div></a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNavAltMarkup">
<div className="navbar-nav">
<a className="nav-item nav-link active" href="#">Home <span className="sr-only">(current)</span></a>
<a className="nav-item nav-link" href="#">By State</a>
</div>
</div>
</div>
</nav>
And then in my webpack.config.js I have the following in the module section:
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
Welcome to StackOverflow!
With this line, you have imported the image.
import logoFinal from './logoFinal.png';
The logoFinal variable will be the actual image-path, which will be generated by webpack. So you can use it in the <img /> tag as the src attribute.
<img src={logoFinal} />
You webpack config looks weird, because you have defined two rules for images. The later one with require.resolve('url-loader') seams to be correct.
I'm working with Natalie. I've removed the extra url-loader in the web pack and kept the second. I've tried the suggestions and the image still renders as broken. I see the img in the html as this: http://localhost:3000static/media/logoFinal.fb830421.png
I've also attempted to use file-loader.
I have a ruby on rails app, and i'm using HAML for HTML structure,
I'd like to minify/uglify the output "html", remove unnecessary whitespaces and new lines.
Something like this:
<div class='wrapper v2-header-wrapper' id='fix-content'><div class='header header-search' style='text-align: center !important;'><nav class='navbar navbar-toggleable-md navbar-light bg-faded navbar-expand-lg'><button class='navbar-toggler navbar-toggler-right' onclick='openNav()' type='button'><span class='navbar-toggler-icon'><i class='fa fa-bars'></i></span></button><a class='navbar-brand mobile pull-left' href='/'><i class='fa fa-search'></i>
Instead of this:
<div class='wrapper v2-header-wrapper' id='fix-content'>
<div class='header header-search' style='text-align: center !important;'>
<nav class='navbar navbar-toggleable-md navbar-light bg-faded navbar-expand-
lg'>
<button class='navbar-toggler navbar-toggler-right' onclick='openNav()'
type='button'>
<span class='navbar-toggler-icon'>
<i class='fa fa-bars'></i>
</span>
</button>
<a class='navbar-brand mobile pull-left' href='/'>
<i class='fa fa-search'></i>
Your help is highly appreciated, thanks in advance.
Have a go at this:
app/middleware/html_minifier.rb
class HtmlMinifier
def initialize(app)
#app = app
end
def call(env)
# Call the underlying application, return a standard Rack response
status, headers, response = #app.call(env)
# Make sure we don't process CSS or JavaScript
if headers["Content-Type"] =~ /text\/html/
response.each do |chunk|
[
# Join lines
[/[\r\n]+/, ""],
# Remove whitespace between tags
[/>\s+</, "><"],
# Remove comments
[/<!--(.|\s)*?-->/, ""],
# Remove whitespace in inline JavaScript
[/;\s+/, ";"],
[/{\s+/, "{"]
].each do |regex, substitute|
chunk.gsub! regex, substitute
end
end
end
# Return the new Rack response
[status, headers, response]
end
end
There is a Gem for that. Just add this to your Gemfile:
gem 'htmlcompressor', '~> 0.4.0'
And this to your application.rb:
config.middleware.use HtmlCompressor::Rack
I'm using that within a Rails 6 application and it worked out of the box.
I would also recommend to enable GZip compression. You can do that with this middleware:
config.middleware.use Rack::Deflater
No external Gem needed for the last middleware.
I am currently finishing the Authentication side of my server and could use some help.
I'm trying to disable and enable specific tabs depending on wether an User is authenticated. As I was following a video (part 8), the author was using if conditions ( {{#if}} {{/if}} ) in the HTML file to check if a variable in the app.js file was true or not.
I tried it but with no success. Is there a I need to pass in the top of the HTML file? Or is there a better way of doing it?
app.js:
app.use(function(req, res, next) {
res.locals.isAuthenticated = req.isAuthenticated(); //variable in question
next();
});
HTML:
<ul class="nav navbar-nav navbar-right">
{{#if isAuthenticated}} //check if this variable is true or not and if so, show the following elements
<li class="nav-item" class="navbar-right">
<a class="nav-link" href="/Profile">Profile</a>
</li>
<li class="nav-item" class="navbar-right">
<a class="nav-link" href="/Logout">Logout</a>
</li>
{{else}}
<li class="nav-item" class="navbar-right">
<a class="nav-link" href="Register.html">Register</a>
</li>
<li class="nav-item" class="navbar-right">
<a class="nav-link" href="Login.html">Login</a>
</li>
{{/if}}
</ul>
Thanks in advance!
Edit 1: Better explanation
The best option is to use view engine (e.g. EJS) and then render the view with given variables.
app.set('view engine', 'ejs')
^ to set view engine (firstly npm install ejs)
app.set('views', './views')
^ allows you to set your views directory
Then create views directory and, for example, index.ejs file:
<h1> <%= title %> </h1>
Next, write your route:
app.get('/', (req, res) => {
res.render('index', { title: 'Sample title' }) // refers to views/index.ejs
})
Within render method you can pass an object (2nd argument) with parameters that you can use in your view. Further info: http://www.embeddedjs.com/