Hotwire Discussion

How to make Turbo Drive work with php files and query strings

I just got to know the Hotwire concept and I was playing around with it. I don’t have a Rails background, I’m just playing around with PHP.

I have pages like: index.php?page=0, index.php?page=1 etc.

I got Turbo Drive (7.0.0 beta 3) to work with standard HTML pages by importing like this:

<script type="module">
import hotwiredTurbo from 'https://cdn.skypack.dev/pin/@hotwired/turbo@v7.0.0-beta.3-tvFsO8IW4m2YjmlcLZZq/min/@hotwired/turbo.js';
</script>

I also have checked the old Turbolinks documentation and could get Turbolinks 5.2.0 to work with PHP like this:

<script>
Turbolinks.Location.prototype.isHTML = function() {
   var extension = this.getExtension()
    return extension == null ||
           extension === ".php" ||
           extension.match(/^\d/)
}
</script>

Thanks to this Github issue.

How would I do this with Turbo drive?

Replacing Turbolinks.Location.prototype.isHTML with hotwiredTurbo.Location.prototype.isHTML doesn’t work.

Probably due the fact it’s imported as a module right now instead of a script.

Probably I miss something trivial regarding JavaScript modules (can I compile it to a script?) and how I can get Turbo Drive to work with php by modifying the isHTML prototype.

1 Like

I had a similar problem getting .aspx extensions to work. This snippet of code below seems to be working for me. You should be able to replace aspx with php, and be good to go. So far, I haven’t encountered problems with query strings. It looks like they should just work.

let isHtml = function (testing) {
    let components = testing.pathname.split("/").slice(1);
    let lastPathComponent = components.slice(-1)[0];
    let extension = (lastPathComponent.match(/\.[^.]*$/) || [])[0] || "";
    
    return location.origin === testing.origin && !!extension.match(/^(?:|\.(?:htm|html|xhtml|aspx))$/)
}

isHtml = isHtml.bind(Turbo.navigator.adapter.session);
Turbo.navigator.adapter.session.locationIsVisitable = isHtml;
1 Like

Thanks! I’ll try it out.

Absolutely. As a heads up, I pushed this change over to another test site of mine, and it didn’t work right off. That site was running “beta.2”. Upgrading it to “beta.4” was all I needed in order to get that site working.

1 Like