Linking to dynamic routes in Next.js - javascript

When I use the next/link component to link my pages together, I ended up having to specify both the "server side" URL and the queryparam-eterized URL.
An example could be a dynamic /post/:id route that is served by the pages/post.js file:
<Link href="/post?id=2" as="/post/2"><a>Go to post number 2</a></Link>
Is there a different way to do this? It's cumbersome to remember to do this everywhere I want to have a dynamic route.

The href is always necessary as it point to the page that will take care of rendering the content. However the as prop is optional, it's only used to "prettify" the URL shown to the user.
Imagine you land on a site and you see www.mysite.com/post?id=121, looks uglier than just /post/2.
This is still cumbersome, hence there are a few nice libraries that make this easier, the most popular AFAIK is https://www.npmjs.com/package/next-routes, this package makes your life easier when using Link, however you need to write down your own routes.

Related

How to do localized routes in sapper

I am converting a svelte website to a sapper website. The current routing library had the ability to specify aliases for routes, so in my localized case, mydomain.com/hello-world and mydomain.com/vamos-companeros would be the same route/component, only the language on the page would change. I read this in the docs:
If you want to capture more params, you can create nested folders using the same naming convention: [slug]/[language].
but that unfortunately does not fit my use case. Anybody an idea whether and how this is accomplishable? Thanks in advance.
The way I did it now was to create a common component _component.svelte which would not get used as a route and move all my shared logic there. The components hello-world.svelte and vamos-companeros.svelte would reset title and meta tags and then pass the text for the page to _component.svelte, which renders them together with other shared assets like images.

Get data from another HTML page

I am making an on-line shop for selling magazines, and I need to show the image of the magazine. For that, I would like to show the same image that is shown in the website of the company that distributes the magazines.
For that, it would be easy with an absolute path, like this:
<img src="http://www.remotewebsite.com/image.jpg" />
But, it is not possible in my case, because the name of the image changes everytime there is a new magazine.
In Javascript, it is possible to get the path of an image with this code:
var strImage = document.getElementById('Image').src;
But, is it possible to use something similar to get the path of an image if it is in another HTML page?
Assuming that you know how to find the correct image in the magazine website's DOM (otherwise, forget it):
the magazine website must explicitly allow clients showing your website to fetch their content by enabling CORS
you fetch their HTML -> gets you a stream of text
parse it with DOMParser -> gets you a Document
using your knowledge or their layout (or good heuristics, if you're feeling lucky), use regular DOM navigation to find the image and get its src attribute
I'm not going to detail any of those steps (there are already lots of SO answers around), especially since you haven't described a specific issue you may have with the technical part.
You can, but it is inefficient. You would have to do a request to load all the HTML of that other page and then in that HTML find the image you are looking for.
It can be achieved (using XMLHttpRequest or fetch), but I would maybe try to find a more efficient way.
What you are asking for is technically possible, and other answers have already gone into the details about how you could accomplish this.
What I'd like to go over in this answer is how you probably should architect this given the requirements that you described. Keep in mind that what I am describing is one way to do this, there are certainly other correct methods as well.
Create a database on the server where your app will live. A simple MySQL DB will work, but you could use anything. Create a table called magazine, with a column url. Your code would pull the url from this DB. Whenever the magazine URL changes, just update the DB and the code itself won't need to be changed.
Your front-end code needs some sort of way to access the DB. One possible solution is a REST API. This code would query the DB for the latest values (in your case magazine URLs), and make them accessible to your web page. This could be done in a myriad of different languages/frameworks, here's a good tutorial on doing something like this in Node.js and express (which is what I'd personally use).
Finally, your front-end code needs to call your REST API to get the updated URLs. This needs to be done with some kind of JavaScript based language. jQuery would make this really easy, something like this:
$(document).ready(function() {
$.Get("http://uri_to_your_rest_api", function(data) {
$("#myImage").attr("scr", data.url);
}
});
Assuming you had HTML like this:
<img id="myImage" src="">
And there you go - You have a webpage that pulls the image sources dynamically from your database.
Now if you're just dipping your toes into web development, this may seem a bit overwhelming. But I promise you, in the long run it'll be easier then trying to parse code from an HTML page :)

How can I make 'AJAX templates' in Pylons?

I've been getting into Pylons lately and was wondering how I could go about easily integrating AJAX functionality into my websites.
Basically, lets say I had a login form that usually gets accessed via site.com/user/login. Now, generally, this will be handled via something like:
class UserController(BaseController):
def login(self):
render('/login.html')
login.html would be a template that inherits the base, has a header, footer and navigation sidebar. A plani, simple website.
How could I AJAXify this? I would need to create two login.html templates, right? What would be a good way to handle the controller's login() method? Should I set a GET variable of something like &ajax=true then check for that when issuing render()?
I want a nice and clean way to choose how my controllers render content instead of some ugly hack (like the GET method above).
Thoughts?
All modern Javascript libraries set an "X-Requested-With: XMLHttpRequest" header in their AJAX wrappers. As a convenience, Pylons sets the request.is_xhr boolean if it finds this header.
Conditional inheritance is a little tricky in Mako because of how <%inherit> is handled, but here's what you do:
Change the render() call in your controller to render('/login.html', {'ajax': request.is_xhr})
In your template, separate out anything you don't want in your AJAX template using template inheritance.
Use an <%inherit> something like this:
<%inherit file="${None if context.get('ajax') else 'login_base.html'}"/>
(Note: There's nothing special about the render() syntax used. You could just as easily use c.ajax = request.is_xhr and context.get('c').ajax instead)
I'm not sure why your AJAX code would want to do a GET on that login page -- GET is only for getting information, and what info would the JS code client-side want to obtain from a login form?
Anyway, assuming there are pages that you want AJAX code to be able to GET in order to obtain useful info, I recommend a query string such as ?format=json to allow such requests to explicitly ask for "useful JSON-format info only, no decoration please".
Not only does this approach allow your app to know that this is an automated request (AJAX or otherwise, who cares? point is, no cosmetics are to be sent in response, just useful info!) but specifically that the requested format is JSON (so, should you ever want to supply XML or whatever as an alternative, there's an obvious growth path -- ?format=xml and the like).
There is nothing particularly Python-specific, much less Pylons-specific, in this -- it's the approach I would recommend for any "mixed" site (able, at least in some pages, to respond in more than one format, e.g. HTML with decorations or JSON, at clients' choice) no matter what sever-side language it was planning on using.
If your rendering is always of a form such as somefunction(sometemplate, somecontext), though, you may tweak things to ensure that the somefunction also gets the crucial bit about requested format -- if the requested format is JSON (or, who knows, in the future maybe XML or whatever) then somefunction knows it can ignore the template (which after all is or should be a purely view related functionality, and therefore should have presentation contents only) and just proceed to render the info that's in the context as JSON or whatever.
The author of Mako himself wrote a blog post that you might find interesting.
The main point is a function to render a single "def" of a template:
def render_def(template_name, name, **kwargs):
from pylons.templating import pylons_globals
globs = pylons_globals()
if kwargs:
globs = globs.copy()
globs.update(kwargs)
template = globs['app_globals'].mako_lookup.get_template(template_name).get_def(name)
return template.render(**globs)

Run a JavaScript function from a URL

I need to link to a page that uses javascript to create the appearance of different pages. Each of the links on the page I am pointing to calls a javascript function that produces the "new" page. So, if I just link to the page, I get the default configuration. But what I need to link to is a particular configuration after the js function has run.
At first I thought I would be able to append the function to the url, but apparently that functionality is not supported for security reasons (is this correct?). Is it possible to post the values?
Does anyone know how I can display the correct configuration?
In the general case, no, it's not possible, which is why these sort of JavaScript-only pages are an inaccessible, unusable total pain in the neck and people should stop creating them, the idiots.
If you are lucky and the site you're talking about has actually Done It Properly, then they'll have used #fragment navigation, so when you click a link it does a history-able and bookmark-able navigation, updating the URL to one with a #something at the end that you can use to navigate back there. If you're really lucky, there might even be a fallback URL for non-JavaScript browsers that you could link to. But more often all there is is a JS function, which you can't link to or invoke outside of that site, leaving you quite out of luck should you want to deep-link anything.
(Did we learn nothing from the <frame> fiasco, guys? All you trendy webmasters hacking up clever-clever swooshy jQuery-animated load()-powered multiple-pages-in-one sites are churning out rubbish that is no better than the frame-addled worst of the Netscape 3 era. Stop it. Seriously.)
Okay, I was given the solution by a friend. It seems I should answer my own question. In fact, I felt a little silly once I saw how simple the solutions was. I just forgot how to plant "posts" in a URL. It seems the question itself was erroneous.
All I really needed to do was set some Javascript variables in a page I don't own. Solution looks something like this.
http://www.apage.com/control.aspx?var1=someVal&var2=someVal...&varn=someVal
Thanks to those who responded.
The owner of the page could do you a favour and provide a mechanism to run functions depending on a value in the querystring.
Otherwise there may be something that can be done with ajax but it could be messy.

Help me to understand <script src="some.js?param1=one;param2=two" />

I observed chunks like below sometimes on web pages. So i am curious to know what this really does? or why its written in such a way?
<script src="somefile.js?param1=one&param2=two" />
i can only make out following few intentions behind it
Its not page URL (i mean .aspx/.php/.jsp etc.) so its not hacking kind of code where user can add code like this to pass data without getting users attention as its tag which does not render on UI OR implementing old type of AJAX alternative
This kind of URL param are useful if user do not wish the JS file (any other resource like image) to get cached. This can be quick way to manage caching
But i am unable to figure out following
Looks like page URL parameters but are these parameters anyway readable in JavaScript file and have some additional utility?
Do these parameters have any extra role to play here ?
What are the other possible practical scenarios where code like this can be/is used?
So please provide some inputs related with the same
Thanks,
Running Non-JS Code within .js Extensions
In cases like this, that source .js file might (given proper server-configurations) actually have PHP/.NET code within it, which can read those appended values.
As you said, Avoiding Cache...
Additionally, people will at times append a random string at the end of their referenced elements to avoid loading cached data.
The URL having '.js' means nothing. It could still be handled by a server-side script like an ASP or PHP.
Either the javascript file is not static (it is generated by the server based on the parameters in its querystring)
OR
In the JavaScript file itself, you can have it check its own querystring parameters (not just that of the page, but that of the javascript source url).
OR
(This doesn't exactly match your scenario, but) you can also add parameters at the end of image and script urls as a way of versioning. The version with the url="somescript.js?V=3" will be cached by the user until the page then changes and the url is not="somescript.js?V=4". The file will be replaced by the version on the server no matter what the browser setting may be.
My guess (without looking at this specific case) is that the javascript file is reading its own querystring. I have done this, and its very helpful.
Looks like page URL parameters but are these parameters anyway readable in JavaScript file and have some additional utility?
Yes you can read them in JavaScript, Scriptaculous uses that approach for loading modules, eg:
<script type="text/javascript" src="scriptaculous.js?load=effects,dragdrop">
</script>
Do these parameters have any extra role to play here ?
What are the other possible practical scenarios where code like this can be/is used?
That can be also used for server-side script joining and minifying, of course using some url rewriting technique to have the .js extension, and as you say, it's a common technique to add timestamp parameters to break the browser cache.
It can be used for three different reasons:
1) To generate the JavaScript file in the server depending on the parameters;
2) To avoid caching;
3) To pass parameters to JavaScript itself
An example of this in practice would be a server side handler for somefile.js that uses the parameters (names of other scripts) to determine which scripts are actually required and combine/minify them, returning them as a single somefile.js script file.

Categories

Resources