Using Page anchors on django - google-app-engine

I would like to have AppEngine render an html page that auto scrolls to an html anchor point. I'm not sure how and where to put that type of instruction.
template_values = {
'foo' : 'foo',
'bar': 'bar',
'anchor' : '#MyPageAnchor' # ?? Something like this...
}
path = os.path.join(os.path.dirname(__file__), fileName)
self.response.out.write(template.render(path, template_values))
Is this possible? How do I accomplish this?

There's nothing App Engine specific here. You simply have to redirect the user to a URL that includes the anchor (eg, http://example.com/foo#anchor).

Related

wagtail 4.0/ How return urls (templates) for preview in admin board from #path

class ProductIndexPage(RoutablePageMixin, Page):
subpage_types = ['ProductPage']
parent_page_types = ['home.HomePage']
def live_categories(self):
all_products_live_id = ProductPage.objects.live().values_list('categories_id', flat=True)
list_live_id_uniqe = list(set(all_products_live_id))
live_cat = ProductCategory.objects.filter(id__in=list_live_id_uniqe).order_by('-id')
return live_cat
#path('')
#path('all-categories/')
def all_category_page(self, request):
productpages = self.get_children().live().order_by('-first_published_at')
return self.render(request, context_overrides={
'title': self.title,
'productpages': productpages,
'live_categories': self.live_categories,
})
#path('<str:cat_name>/', name='cat_url')
def current_category_page(self, request, cat_name=None):
productpages = ProductPage.objects.live().filter(categories__slug__iexact=cat_name).order_by \
('-first_published_at')
current_cat = self.live_categories().get(slug=cat_name).name
return self.render(request, context_overrides={
'title': "%s" % current_cat,
'productpages': productpages,
'live_categories': self.live_categories,
})
#path('<str:cat_name>/<str:prod_name>/')
def product_page(self, request, cat_name=None, prod_name=None):
product = ProductPage.objects.get(categories__slug__iexact=cat_name, slug=prod_name)
return self.render(request, context_overrides={
'product': product},
template="products/product_page.html",)
I can't edit page in wagtail admin menu from path:
#path('<str:cat_name>/<str:prod_name>/')
My page tree in admin:
root/products/<prod_name>
How to change route in Admin for editing pages from wagtal button or for preview in Admin?
I am newbie, plz show me example.
sorry for English)
With RoutablePageMixin there is only one page - and it displays differently depending on the parameter sent on the url. Unfortunately, this means you can't preview the category version of your page, current_category_page.
But it looks like the product page you are routing too as #path('str:cat_name/str:prod_name/') should be displaying the same page as you serve from the ProductPage's own url. So the ProductPage you see in the preview ProductIndexPage + 'str:cat_name/str:prod_name/'

How to change domain name (entire url) in react-router-dom

If I am in http://localhost:3000/Authpage I want to redirect to new URL http://www.example.com/
Usehostory() -> histor.push() is appending new url to old url.
http://localhost:3000/Authpage/http://www.example.com/
But I need new location something like below
http://www.example.com/
You can have a look at this thread here for an answer.
To summarize it, in your event handler you can add
const eventHandler = () => {
window.location.assign('http://www.example.com/')
}
However, the way I see it, it's just easier to create a simple regular HTML <a> tag:
<a href='http://www.example.com/'>click to redirect</a>
you have 2 options
use tag to redirect the user into a new web page.
or use one of the javascript methods like window.open("yourUrl.com")
but be careful when you are using javascript methods to redirect the user because the safari browser would not let you use some of them( because of some security filters)
You should use window.location.assign. For example
handleClick() {
window.location.assign('http://www.example.com/');
}
render() {
return (
<button onClick={this.handleClick.bind(this)} />
);
}`

CakePHP adding language parameter to URLs

I implemented the solution at this article.
"beforeFilter" and "_setLanguage" works fine. If URL has language parameter, I can successfully set cookies/session variables. And use it between controllers.
That solution also includes adding url() function to AppHelper.
class AppHelper extends Helper {
function url($url = null, $full = false) {
if(!isset($url['language']) && isset($this->params['language'])) {
$url['language'] = $this->params['language'];
}
return parent::url($url, $full);
}
}
But I have many URLs in my View files that are written without using HtmlHelper. Like this:
// myfile.ctp
<a href="/mypage/">click me plase<a>
So it seems like AppHelper::url solution doesn't fix my issue. What would be better alternative to add language prefix to URLs?
I thought defining a global variable like this:
// AppController::_beforeFilter()
if ($this->request->params['language'] != "")
{
Configure::write('URLprefix', '/'.$this->request->params['language']);
} else {
Configure::write('URLprefix', '');
}
Then change view file like this:
// myfile.ctp
<a href="<?php echo URLprefix; ?>/mypage/">click me plase<a>
But it doesn't seem a good way. Is there a better way to add prefix to URLs. Or should I add to all links by hand ?
Related:
Adding a prefix to every URL in CakePHP
CakePHP 2.x i18n route
CakePHP 2.1 URL Language Parameter
You should generate all links and URLs within your application using HtmlHelper::link() and HtmlHelper::url()
This will make sure that your Routes are taken into account when generating URLs (Reverse routing)
For example, if you decide to define a 'friendly' URL Route /logout for /users/logout, then this:
echo $this->Html->link('Log out', array(
'controller' => 'users',
'action' => 'logout'
));
Will create this link:
<a href='/logout'>Log out</a>
If you later decide to modify the 'friendly' URL Route (/sign-out) for the logout URL, then all links in your application will automatically be adjusted.
The same call to the HtmlHelper, will now output:
<a href='/sign-out'>Log out</a>
Read more on this subject here:
Reverse Routing

window.reload reloads before fetching response

i am using jqueryMobile with backbonejs.
task: login form with email and password fields. Fill the form and redirect to same form with 3 links:
update profile
change pwd
logout
Problem: when logout is clicked i wish to redirect it back to the login form(same page) with message-"successfully logged out."
what i did:
in view.js:
$('#logoutClick').click(function() {
console.log("hi");
this.collection = new Fan();
this.collection.logoutFan();
window.location.reload(true);
});
in myController(of cakephp):
public function mobile_logout() {
$status = true;
$event = array();
$data = array();
$this->Auth->logout();
$this->Session->setFlash('Successfully Logged out', 'flash_failure');
$this->Session->delete('Auth.Fan');
$this->set('status',$status);
$this->set('output',$data);
$this->render('/Layouts/json/mobile',false);
}
now when i click on logout, the page is redirected but the message is not rendered.(i guess the page reloads before fetching the response).
When i inspect element in chrome-I can see logout.json with no available preview(json response from controller isn't there).
How do i solve this?
Don't do reload. Use redirect:
window.location = 'yourloginpage?msg=success';
As jQuery mobile simulates one big web page, you cannot reffer to another pages. Using:
window.location.reload(true);
Opens a new view, where jQM starts working once again (it downloads all header files etc). It works like links with rel="external"
If you want to keep jQM working in such case you have to add all headers to your html files and you should be aware you cannot reffer to previous page because it is deleted from DOM.
I did it some different way. It is not perfect:) Try to redirect to another page using $.mobile.changePage("./newpage.html). In this new page add event pageinit and redirect back to the start page.

NancyFX Catch All route

Does NancyFX supports ASP.NET MVC like 'Catch All' route? I need one, that basically match every URL. This is very handy for building up Single Page applications.
Is that possible?
Tested in Nancy version 0.23.2
Get[#"/(.*)"] did not work for me as a catch-all route. The routes "/", "/foo/bar", and longer routes would not catch. It seems like there's no getting around having to define a Get["/"] route for the root URL. Nothing else seems to catch it (tried Get["{uri*}"]). Here's how I ended up defining my routes (keep in mind I'm doing this for an Angular application):
Get["/views/{uri*}"] = _ => { return "A partial view..."; };
Get["/"] =
Get["/{uri*}"] = _ =>
{
var uri = (string)_.uri;// The captured route
// If you're using OWIN, you can also get a reference to the captured route with:
var environment = this.Context.GetOwinEnvironment();// GetOwinEnvironment is in the 'Nancy.Owin' namespace
var requestPath = (string)environment["owin.RequestPath"];
return View["views/defaultLayout.html"];
};
It's important to understand Pattern Scoring. The route patterns are weighted, if two routes match the same url segment, the higher score wins. The catch-all pattern is weighted 0 and even though the /views/{uri*} route pattern is also a catch-all, it starts with a literal, which is weighted 10000, so it will win out on all routes that start with /views.
Here's more info on Accessing Owin's Environment Variables. Note that the captured uri variable and requestPath will be slightly different. The requestPath will start with a / where as the uri variable will not. Also, if the matched route pattern is Get["/"], uri will be null and requestPath will be "/".
The Views route will return a partial html file, based on the url path, and all other routes will return the default Layout page that will bootstrap the SPA.
Yes, using Regex
Get[#"/(.*)"] = parameters => {
return View["viewname", parameters];
};
But you don't really need it for building a Single Page Application with NancyFX - you can just use Get and Post with all your routing logic and still have a single page app.
An updated answer for whom #synhershko 's solution does not work. Try:
Get[#"^(.*)$"] = parameters => {
return "hi";
};
This will capture all paths except for the index page. I am not sure if this will work in the context of Angular, but this worked for me when trying to hack together a simple server with just one handler.
Answer provided by #synhershko does not work for me. It does not handle /users/2 or any other route containing more segements.
Below code works on my machine ;) :
public class IndexModule : NancyModule
{
dynamic IndexPage() { return View["Index"]; }
public IndexModule()
{
Get["/"] = _ => { return IndexPage(); };
Get["/(.*)"] = _ => { return IndexPage(); };
Get["/(.*)/(.*)"] = _ => { return IndexPage(); };
Get["/(.*)/(.*)/(.*)"] = _ => { return IndexPage(); };
}
}
My solution is not perfect, cause it does not match everything. I repeated as many '/(.*)' as in my longest Angular route.

Resources